设计模式行为型(排除过多的ifelse,无需反射和注解的实现方式)
1.定义一个父类 interface
public interface IntefaceObj { Object todo(Object obj);
}
2.两个IntefaceObj 的实现类 实现各自的逻辑,并提供一个获取实例的单例方法
public class ObjA implements IntefaceObj{ private static ObjA objA = null;
@Override
public Object todo(Object obj) {
//此处执行A的业务逻辑
System.out.println("this is A");
return null;
}
public static ObjA getInstance() {
if (objA == null) {
synchronized (ObjA.class) {
objA = new ObjA();
}
}
return objA;
}
}
public class ObjB implements IntefaceObj{ private static ObjB objB = null;
@Override
public Object todo(Object obj) {
//此处执行B的业务逻辑
System.out.println("this is B");
return null;
}
public static ObjB getInstance() {
if (objB == null) {
synchronized (ObjB.class) {
objB = new ObjB();
}
}
return objB;
}
}
3.定义一个枚举 通过不同的类型获取不同的对象实例
public enum ApplyEnum { OPT_A("typeA",ObjA.getInstance()),
OPT_B("typeB",ObjB.getInstance());
private String code;
private IntefaceObj option;
ApplyEnum(String code, IntefaceObj option) {
this.code = code;
this.option = option;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public IntefaceObj getOption() {
return option;
}
public void setOption(IntefaceObj option) {
this.option = option;
}
public static IntefaceObj getOpt(String code){
for (ApplyEnum value : ApplyEnum.values()) {
if(value.getCode().equals(code)){
return value.getOption();
}
}
return null;
}
}
4.测试
public class JunitTest { public static void main(String[] args) {
test("typeA");
test("typeB");
System.out.println(1);
}
public static void test(String type){
IntefaceObj opt = ApplyEnum.getOpt(type);
if(Objects.isNull(opt)){
System.out.println("opt is null");
return;
}
Object res = opt.todo("参数");
}
}
以上是 设计模式行为型(排除过多的ifelse,无需反射和注解的实现方式) 的全部内容, 来源链接: utcz.com/z/518623.html