工厂模式的实践
使用场景
开发中,有时需要 根据不同的类型执行不同的实现类。
比如,第一次审核,第二次审核, 都是审核,但具体实现不一样。
可以使用工厂模式。
基础接口:
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();
}
}