委派模式
委派模式(Delegate)原理:
類B和類A是兩個(gè)互相沒有任何關(guān)系的類,但是B具有和A一模一樣的方法和屬性;并且調(diào)用B中的方法/屬性就是調(diào)用A中同名的方法和屬性。
java各種設(shè)計(jì)模式之間都有共同點(diǎn),比如委派模式與代理模式和策略模式有一點(diǎn)相像,這里介紹一下區(qū)別:
-
委派模式:上面概念說了,A和B兩個(gè)類沒有任何關(guān)系,但是A和B的方法在方法名、參數(shù)、返回值一模一樣。
public class EmployeeA { public void doing(String command) { System.out.println("我是員工A,我現(xiàn)在開始干" + command + "工作"); } }public class EmployeeB { public void doing(String command) { System.out.println("我是員工B,我現(xiàn)在開始干" + command + "工作"); } }-
UML類圖
委派模式.png
-
-
代碼
-
IEmployee 頂層接口
public interface IEmployee { public void doing(String command); } -
IEmployeeA 員工A實(shí)現(xiàn)頂層接口
public class EmployeeA implements IEmployee { @Override public void doing(String command) { System.out.println("我是員工A,我現(xiàn)在開始干" + command + "工作"); } } -
IEmployeeA 員工B實(shí)現(xiàn)頂層接口
public class EmployeeB implements IEmployee { @Override public void doing(String command) { System.out.println("我是員工B,我現(xiàn)在開始干" + command + "工作"); } } -
Leader 項(xiàng)目經(jīng)理
public class Leader implements IEmployee { private Map<String,IEmployee> targets = new HashMap<String,IEmployee>(); public Leader() { targets.put("加密",new EmployeeA()); targets.put("登錄",new EmployeeB()); } //項(xiàng)目經(jīng)理自己不干活 public void doing(String command){ targets.get(command).doing(command); } } -
Boss 老板提出需求
public class Boss { public void command(String command,Leader leader){ leader.doing(command); } } -
DelegateTest 測試類
public class DelegateTest { public static void main(String[] args) { //客戶請求(Boss)、委派者(Leader)、被委派者(IEmployee) //委派者要持有被委派者的引用 //代理模式注重的是過程, 委派模式注重的是結(jié)果 //策略模式注重是可擴(kuò)展(外部擴(kuò)展),委派模式注重內(nèi)部的靈活和復(fù)用 //委派的核心:就是分發(fā)、調(diào)度、派遣 //委派模式:就是靜態(tài)代理和策略模式一種特殊的組合 new Boss().command("登錄",new Leader()); } } -
輸出
我是員工B,我現(xiàn)在開始干登錄工作
-
-
代理模式:更注重過程,什么意思呢?
- 保護(hù)被代理對象的代碼
- 對被代理對象方法執(zhí)行前后,進(jìn)行業(yè)務(wù)處理,即增強(qiáng)代碼
public class Proxy implements Subject { private Subject subject; public Proxy(Subject subject){ this.subject = subject; } public void request() { //執(zhí)行前 before(); //執(zhí)行被代理類 subject.request(); //執(zhí)行后 after(); } public void before(){ System.out.println("called before request()."); } public void after(){ System.out.println("called after request()."); } }
- 策略模式:典型的面向接口編程,一般情況下一個(gè)接口實(shí)現(xiàn)類只會(huì)有一個(gè)方法,且一旦新建就不會(huì)修改,新增業(yè)務(wù)只會(huì)新建一個(gè)實(shí)現(xiàn)類。
