有时后经常需要写很多的if判断语句,导致了代码的十分冗余,可读性不高,下面以工厂设计模式+策略设计模式提供一种可替代的写法,简化代码
工厂设计模式:Factory2
import com.google.common.collect.Maps; import org.springframework.util.StringUtils; import java.util.Map; /** * 工厂设计模式 */ public class Factory2 { private static Map<String, AbstractHandler> strategyMap = 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); } }
模板方法设计模式 AbstractHandler
/** * 模板方法设计模式 */ public abstract class AbstractHandler implements InitializingBean { public void AAA(String name) { throw new UnsupportedOperationException(); } public String BBB(String name) { throw new UnsupportedOperationException(); } }
模板方式:LiSiHandler2
@Component public class LiSiHandler2 extends AbstractHandler { @Override public String BBB(String name) { // 业务逻辑B return "李四完成任务B"; } @Override public void afterPropertiesSet() throws Exception { Factory2.register("李四", this); } }
模板方式:TianQiHandler2
import org.springframework.stereotype.Component; @Component public class TianQiHandler2 extends AbstractHandler { @Override public void AAA(String name) { // 业务逻辑A System.out.println("田七完成任务A"); } @Override public void afterPropertiesSet() throws Exception { Factory2.register("田七", this); } }
模板方式:WangWuHandler2
import org.springframework.stereotype.Component; @Component public class WangWuHandler2 extends AbstractHandler { @Override public String BBB(String name) { // 业务逻辑B return "王五完成任务B"; } @Override public void afterPropertiesSet() throws Exception { Factory2.register("王五", this); } }