委派模式

委派模式

經過學習後整理

委派模式(Delegate Pattern)的基本作用就是
負責任務的調用和分配任務,跟代理模式很像,可以看做是一種特殊情況下的靜態代理的全權代理,但是代理模式注重過程,而委派模式注重結果。委派模式在Spring 中應用非常多,常用的DispatcherServlet 其實就是用到了委派模式。

在這裏插入圖片描述

老闆(Boss)給項目經理(Leader)下達任務,項目經理會根據
實際情況給每個員工派發工作任務,待員工把工作任務完成之後,再由項目經理彙報工作進度和結果給老闆。

//員工
public interface IEmployee {

    void doing(String command);

}
public class EmployeeA implements IEmployee {
    @Override
    public void doing(String command) {
        System.out.println("A員工,開始做" + command + "工作");
    }
}
public class EmployeeB implements IEmployee {
    @Override
    public void doing(String command) {
        System.out.println("B員工,開始做" + command + "工作");
    }
}

public class Leader implements IEmployee {

    private Map<String, IEmployee> map = new HashMap<String, IEmployee>();

    public Leader() {
        map.put("端茶", new EmployeeA());
        map.put("倒水", new EmployeeB());
    }

    @Override
    public void doing(String command) {
        if (map.get(command) == null) {
            System.out.println("沒人會做");
            return;
        }
        map.get(command).doing(command);
    }
}
public class Boss {

    public void command(String command, Leader leader) {
        leader.doing(command);
    }

}
public class Test {

    public static void main(String[] args) {
        Boss boss = new Boss();
        boss.command("端茶", new Leader());
        boss.command("倒水", new Leader());
        boss.command("掃地", new Leader());
    }
}

在這裏插入圖片描述

客戶請求(Boss)、委派者(Leader)、被被委派者(Employee)
委派者要持有被委派者的引用
代理模式注重的是過程, 委派模式注重的是結果
策略模式注重是可擴展(外部擴展),委派模式注重內部的靈活和複用
委派的核心:就是分發、調度、派遣
委派模式:就是靜態代理和策略模式一種特殊的組合

發佈了21 篇原創文章 · 獲贊 8 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章