前言
上一篇中介紹了採用表驅動(map)方式和Optional方式取代if...else、switch...case邏輯。本章採用JAVA設計模式之策略模式抽象公共方法,剝離像map這樣的緊耦合操作,對擴展開放,只關心自己的handler邏輯即可。
策略模式是對算法的包裝,是把使用算法的責任和算法本身分割開來,委派給不同的對象管理。策略模式通常把一個系列的算法包裝到一系列的策略類裏面,作爲一個抽象策略類的子類。用一句話來說,就是:“準備一組算法,並將每一個算法封裝起來,使得它們可以互換”。
策略模式UML結構圖:
我們還是繼續上一篇的業務處理,採用策略模式處理消息。首先新建一個AbstractHandler接口:
public interface AbstractHandler {
public void messageHandle();
}
然後新建三個具體的實現handler,分別是ModNewHandler、ModUpdateHandler、ModDeleteHandler,代碼如下:
import org.springframework.stereotype.Component;
@Component
public class ModNewHandler implements AbstractHandler {
@Override
public void messageHandle() {
System.out.println("mode new handler...");
}
}
import org.springframework.stereotype.Component;
@Component
public class ModUpdateHandler implements AbstractHandler {
@Override
public void messageHandle() {
System.out.println("mode update handler...");
}
}
import org.springframework.stereotype.Component;
@Component
public class ModDeleteHandler implements AbstractHandler {
@Override
public void messageHandle() {
System.out.println("mode delete handler...");
}
}
實現HandlerContext類,如下代碼:
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
@Component
public class HandlerContext {
private static Map<Integer, AbstractHandler> map = new HashMap<>();
static {
map.put(0, new ModNewHandler());
map.put(1, new ModUpdateHandler());
map.put(2, new ModDeleteHandler());
}
public AbstractHandler getHandler(Integer type) {
return map.get(type);
}
}
具體的實現類如下:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tv.mgt.msg.MsgInfo;
public class ModMessageApplication {
public static void main(String[] args) {
MsgInfo msgVo = new MsgInfo();
msgVo.setType(0);
Integer type = msgVo.getType();
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"classpath*:spring/context.xml"});
HandlerContext handlerContext = ac.getBean(HandlerContext.class);
AbstractHandler handler = handlerContext.getHandler(type);
handler.messageHandle();
}
}
執行後的結果如下:
mode new handler...
本章通過策略模式替換了if...else、switch...case,其實策略模式應用在很多地方,後續有可能還會介紹。