工厂模式的实践
使用场景
开发中,有时需要 根据不同的类型执行不同的实现类。
比如,第一次审核,第二次审核, 都是审核,但具体实现不一样。
可以使用工厂模式。
基础接口:
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();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-11-11 zookeeper报错: org.I0Itec.zkclient.exception.ZkMarshallingError: java.io.EOFException