責任鏈模式

責任鏈模式

責任鏈模式的定義

應用場景舉例

Android中的Touch事件傳遞java

Html Dom onClick事件傳遞web

Netty中InBound、OutBound消息處理ChannelPipeline設計模式

 

責任鏈模式UML

實際案例

服務器向手機端APP推送消息:服務器

當有網絡而且手機端APP在線時候優先使用WebSocekt;websocket

當手機休眠的時候,沒法使用websocket,改成使用華爲推送服務向手機APP發送消息;網絡

當華爲推送也失敗的時候,改成使用短信息來發送消息。socket

 

public abstract class Handler {
	
	protected Handler mNextHandler;
	public void setSuccessor(Handler h) {
		mNextHandler = h;
	}
	
	public abstract void handleRequest(Message msg) ;
}

 

public class WebSocketHandler extends Handler{

	@Override
	public void handleRequest(Message msg) {
	   if(isOnLine()) {
		    sendSocketMessage();
		    return;
		   
	   }
	   super.mNextHandler.handleRequest(msg);
		
	}

	private void sendSocketMessage() {
		System.out.println("WebSocketHandler sendSocketMessage ");
	}

	private boolean isOnLine() {
		return false;
	}

}

 

public class MiPushHandler extends Handler {

	@Override
	public void handleRequest(Message msg) {
	   if(isCanPush()) {
		    sendPushMessage();
		    return;
		   
	   }
	   super.mNextHandler.handleRequest(msg);
		
	}

	private void sendPushMessage() {
		System.out.println("MiPushHandler sendPushMessage ");
	}

	private boolean isCanPush() {
		return false;
	}

}

 

public class MmsHandler extends Handler{

	@Override
	public void handleRequest(Message msg) {
		
		sendMms();
		
	}

	private void sendMms() {
		System.out.println("MmsHandler sendMms ");
	}

}
public static void main(String[] args) {
	
        WebSocketHandler webSocketHandle = new WebSocketHandler();
        MiPushHandler miPushHandler = new MiPushHandler();
        MmsHandler mmsHandler = new MmsHandler();
        
        webSocketHandle.setSuccessor(miPushHandler);
        miPushHandler.setSuccessor(mmsHandler);
       // 啓動消息泵
        Message msg = new Message();
        webSocketHandle.handleRequest(msg);
        
}

責任鏈模式的優缺點

類似的設計模式

相關文章
相關標籤/搜索