zoukankan      html  css  js  c++  java
  • 委派模式(Delegate Pattern)

    委派模式(Delegate Pattern)

    基本工功能就是任务的调度和分配,将任务的分派和执行进行分离。简而言之,类似于一个代理,在这个代理类中处理的你的需求,至于在内部调用那个实现类去实现,客户端不用管。在某种程度上讲类似于:老板-->经理-->员工

    a scene of  Issue an order to illustrate

    public class Boss {
        public void command(String task,Leader leader){
            leader.doIt(task);
        }
    }

    as a boss I just need to command my employees leaders to do what i want to do

    public interface IEmployee {
        void doIt(String task);
    }
    public class Leader implements IEmployee {
        Map<String,IEmployee> iEmployeeMap=new HashMap<String, IEmployee>();
    
        public Leader() {
            iEmployeeMap.put("Selling",new EmployeeA());
            iEmployeeMap.put("Buying",new EmployeeB());
        }
    
        @Override
        public void doIt(String task) {
            if (!iEmployeeMap.containsKey(task)){
                System.err.println("I have no coworker who can be used to do that!!!");
                return;
            }
            iEmployeeMap.get(task).doIt(task);
        }
    }

    as a leader i need to know which skills my coworkers have(there we use a  Leaders to spread commond made by boss)

    tips:we put point of skill that each employees good at into map, so that if we have other employees, we just need put them into map and do not need to adjust code sharply

    public class EmployeeB implements IEmployee{
        @Override
        public void doIt(String task) {
            System.out.println("to do Buying");
    
        }
    }
    public class EmployeeA  implements IEmployee{
        @Override
        public void doIt(String task) {
            System.out.println("to do Selling");
    
        }

    To test(we just pass on what i want to do then, make leaders to do )

    public class test {
        public static void main(String[] args) {
            new Boss().command("Selling",new Leader());
            new Boss().command("Buying",new Leader());
            new Boss().command("Eating",new Leader());
        }
    }

    How is delegate pattern used into source of code

    java.lang.reflect.Method#invoke

     Sum up

    advantage:

    • uncoupled: divide a monstrous requirement into different part to execute

    disadvantage:

    • if a pretty complex demand we may need to  multilayer delegate

  • 相关阅读:
    【mysql+RBAC】RBAC权限处理(转载:http://www.cnblogs.com/xiaoxi/p/5889486.html 平凡希)
    【小程序】获取微信 自带的 收货地址获取和整理
    【TP3.2】跨库操作和跨域操作
    【JS】一款好用的JS日历选择插件【bootstrap-datetimepicker.js】
    Python 读写文件中w与wt, r与rt的区别
    Python 在序列上跟踪索引和值
    SoapUI 使用变量
    python 跳过可迭代对象的开始部分
    Python 迭代器切片
    Python: 类中为什么要定义__init__()方法
  • 原文地址:https://www.cnblogs.com/UpGx/p/14744261.html
Copyright © 2011-2022 走看看