IF-ELSE 写法
String noDesign() {
String name = "张三";
if (name.equals("张三")) {
// 业务逻辑B
return "张三完成任务BBB";
} else if (name.equals("李四")) {
// 业务逻辑B
return "李四完成任务BBB";
} else if (name.equals("王五")) {
// 业务逻辑B
return "王五完成任务BBB";
} else if (name.equals("赵六")) {
// 业务逻辑A
System.out.println("赵六完成任务AAA");
} else if (name.equals("田七")) {
// 业务逻辑A
System.out.println("田七完成任务AAA");
} else if (name.equals("亢八")) {
// 业务逻辑A
System.out.println("亢八完成任务AAA");
}
return "end";
}
策略模式、工厂模式和模板方法混合使用
策略模式和模板方法写法
定义一个策略模式加模板方法的抽象方法
/**
* 模板方法设计模式
* 使用InitializingBean 使得Bean自动初始化
*/
public abstract class AbstractHandler implements InitializingBean {
public void AAA(String name) {
throw new UnsupportedOperationException();
}
public String BBB(String name) {
throw new UnsupportedOperationException();
}
}
具体策略实现
// 策略1
@Component
public class KangBaHandler extends AbstractHandler {
@Override
public void AAA(String name) {
// 业务逻辑A
System.out.println("亢八完成任务");
}
@Override
public void afterPropertiesSet() throws Exception {
Factory2.register("亢八", this);
}
}
// 策略2
@Component
public class LiSiHandler extends AbstractHandler {
@Override
public String BBB(String name) {
// 业务逻辑B
return "李四完成任务B";
}
@Override
public void afterPropertiesSet() throws Exception {
Factory2.register("李四", this);
}
}
// 策略3
@Component
public class TianQiHandler extends AbstractHandler {
@Override
public void AAA(String name) {
// 业务逻辑A
System.out.println("田七完成任务A");
}
@Override
public void afterPropertiesSet() throws Exception {
Factory2.register("田七", this);
}
}
// 策略4
@Component
public class WangWuHandler extends AbstractHandler {
@Override
public String BBB(String name) {
// 业务逻辑B
return "王五完成任务B";
}
@Override
public void afterPropertiesSet() throws Exception {
Factory2.register("王五", this);
}
}
// 策略5
@Component
public class ZhangSanHandler extends AbstractHandler {
@Override
public String BBB(String name) {
// 业务逻辑B
return "张三完成任务B";
}
@Override
public void afterPropertiesSet() throws Exception {
Factory2.register("张三", this);
}
}
// 策略6
@Component
public class ZhaoLiuHandler2 extends AbstractHandler {
@Override
public void AAA(String name) {
// 业务逻辑A
System.out.println("赵六完成任务");
}
@Override
public void afterPropertiesSet() throws Exception {
Factory2.register("赵六", this);
}
}
工厂模式封装
/**
* 工厂设计模式
*/
public class Factory {
private static Map<String, AbstractHandler> STRATEGY_MAP = Maps.newHashMap();
public static AbstractHandler getInvokeStrategy(String str) {
return strategyMap.get(str);
}
public static void register(String str, AbstractHandler handler) {
if (StringUtils.isEmpty(str) || null == handler) {
return;
}
strategyMap.put(str, handler);
}
}
最终写法
void test() {
String name = "张三";
AbstractHandler strategy = Factory.getInvokeStrategy(name);
String s = strategy.methodA(name);
System.out.println(s);
strategy.methodB(name);
}