有时后经常需要写很多的if判断语句,导致了代码的十分冗余,可读性不高,下面以工厂设计模式+策略设计模式提供一种可替代的写法,简化代码
工厂类:Factory
/** * 工厂设计模式 */ public class Factory { private static Map<String, Handler> strategyMap = Maps.newHashMap(); public static Handler getInvokeStrategy(String name) { return strategyMap.get(name); } public static void register(String name, Handler handler) { if (StringUtils.isEmpty(name) || null == handler) { return; } strategyMap.put(name, handler); } }
策略接口:
import org.springframework.beans.factory.InitializingBean; /** * 策略设计模式 */ public interface Handler extends InitializingBean { public void AAA(String name); }
具体实现的一些策略 KangBaHandler
@Component public class KangBaHandler implements Handler { @Override public void AAA(String name) { // 业务逻辑A System.out.println("亢八完成任务"); } @Override public void afterPropertiesSet() throws Exception { Factory.register("亢八", this); } }
具体实现的一些策略 LiSiHandler
import org.springframework.stereotype.Component; @Component public class LiSiHandler implements Handler { @Override public void AAA(String name) { // 业务逻辑A System.out.println("李四完成任务"); } @Override public void afterPropertiesSet() throws Exception { Factory.register("李四", this); } }
具体实现的一些策略 TianQiHandler
import org.springframework.stereotype.Component; @Component public class TianQiHandler implements Handler { @Override public void AAA(String name) { // 业务逻辑A System.out.println("田七完成任务"); } @Override public void afterPropertiesSet() throws Exception { Factory.register("田七", this); } }
具体实现的一些策略 WangWuHandler
import org.springframework.stereotype.Component; @Component public class WangWuHandler implements Handler { @Override public void AAA(String name) { // 业务逻辑A System.out.println("王五完成任务"); } @Override public void afterPropertiesSet() throws Exception { Factory.register("王五", this); } }
具体实现的一些策略 ZhangSanHandler
import org.springframework.stereotype.Component; @Component public class ZhangSanHandler implements Handler { @Override public void AAA(String name) { // 业务逻辑A System.out.println("张三完成任务"); } @Override public void afterPropertiesSet() throws Exception { Factory.register("张三", this); } }