工厂模式的实践

使用场景

开发中,有时需要 根据不同的类型执行不同的实现类。
比如,第一次审核,第二次审核, 都是审核,但具体实现不一样。

可以使用工厂模式。

基础接口:

public interface MyService {
    void doSomething();

}

实现类一:

@Service
public class FirstMyServiceImpl implements MyService {
    @Override
    public void doSomething() {
        System.out.println("first doSomething");
    }


}

实现类二:

@Service
public class SecondMyServiceImpl implements MyService {

    @Override
    public void doSomething() {
        System.out.println("second doSomething");
    }



}

类型枚举:

public enum TypeEnum {

    FIRST_TYPE(1, "类型一"),

    SECOND_TYPE(2, "类型二"),

    THIRD_TYPE(3, "类型三"),

    ;

    private final Integer value;
    private final String text;

    TypeEnum(Integer value, String text) {
        this.value = value;
        this.text = text;
    }

    public Integer getValue() {
        return this.value;
    }

    public String getText() {
        return this.text;
    }

    public static TypeEnum fromValue(Integer value) {
        for (TypeEnum typeEnum : TypeEnum.values()) {
            if (typeEnum.getValue().equals(value)) {
                return typeEnum;
            }
        }
        return null;
    }

    public static TypeEnum fromText(String text) {
        for (TypeEnum typeEnum : TypeEnum.values()) {
            if (typeEnum.getText().equals(text)) {
                return typeEnum;
            }
        }
        return null;
    }

}




工厂类

/**
 * 工厂类。
 */
@Service
public class MyFactory {

    @Resource
    private FirstMyServiceImpl firstMyService;

    @Resource
    private SecondMyServiceImpl secondMyService;

    /**
     * 根据类型查找服务
     * @param type
     * @return
     */
    public  MyService getServiceByType(int type) {
        if (TypeEnum.FIRST_TYPE.getValue().equals(type)) {
            return firstMyService;
        } else if (TypeEnum.SECOND_TYPE.getValue().equals(type)) {
            return secondMyService;
        } else {
            //也可以不抛异常,设置一个默认的实现类
            throw new IllegalArgumentException("Unknown type");
        }
    }

    /**
     * 根据不同的类型执行不同的实现类。
     * 比如,第一次审核,第二次审核, 都是审核,但具体实现不一样。
     * @param type
     */
    public void doSomethingByType(int type) {
        MyService myService = getServiceByType(type);
        myService.doSomething();
    }



}

posted on   乐之者v  阅读(7)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-11-11 zookeeper报错: org.I0Itec.zkclient.exception.ZkMarshallingError: java.io.EOFException
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示