有時後常常須要寫不少的if判斷語句,致使了代碼的十分冗餘,可讀性不高,下面以工廠設計模式+策略設計模式提供一種可替代的寫法,簡化代碼spring
工廠類: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); } }
策略接口:ide
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); } }