设计模式--委派模式

委派模式

委派模式基本作用就是负责任务的调用和分配,跟代理模式很像。

例子:老板给项目经理下发任务,项目经理把任务分发到员工。

/**
 * 员工类
 */
public interface IEmployee {
    public void doing(String command);
}
public class EmployeeA implements IEmployee {
    public void doing(String command) {
        System.out.println("我是员工A,开始干"+command);
    }
}
public class EmployeeB implements IEmployee {
    public void doing(String command) {
        System.out.println("我是员工B,开始干"+command);
    }
}

/**
 * 项目经理
 */
public class Leader implements IEmployee{

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

    public Leader(){
        targets.put("加盟",new EmployeeA());
        targets.put("登录",new EmployeeB());
    }
    public void doing(String command) {
        targets.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());
    }
}

你可能感兴趣的:(设计模式)