在spring中委派模式用的比較多,在經常使用的23種設計模式中實際上是沒有委派模式的影子的。java
在spring中體現:Spring MVC框架中的DispatcherServlet其實就用到了委派模式。spring
委派模式的做用:基本做用就是負責任務的調用和分配,跟代理模式很像,能夠看作是一種特殊狀況下的靜態代理的全權代理,可是代理模式注重過程,而委派模式注重結果。設計模式
利用一張圖簡述委派模式,下圖簡單說明了老闆把任務給了項目經理,而項目經理將任務拆分,分給一個個it攻城獅,本身沒有作工做,而是把具體工做交給具體的執行者去作。框架
public interface IExcuter { void excute(String command); }
public class ExcuterA implements IExcuter{ @Override public void excute(String command) { System.out.println("員工A 開始作"+command+"的工做"); } }
public class ExcuterB implements IExcuter{ @Override public void excute(String command) { System.out.println("員工B 開始作"+command+"的工做"); } }
public class Leader implements IExcuter { private Map<String,IExcuter> targets = new HashMap<String,IExcuter>(); public Leader() { targets.put("加密",new ExcuterA()); targets.put("登陸",new ExcuterB()); } @Override public void excute(String command) { targets.get(command).excute(command); } }
public class Boss { public static void main(String[] args) { Leader leader = new Leader(); //看上去好像是咱們的項目經理在幹活 //但實際幹活的人是普通員工 //這就是典型,幹活是個人,功勞是你的 leader.excute("登陸"); leader.excute("加密"); } }
參考:https://www.jianshu.com/p/38acf37b1e1fide