委托模式
是存在委托人和执行人,就比如在实际工作中,项目经理将某个任务委托给你去完成,其实交给你、交给他来做都一样,并不执行任务的前后产生变化(区别于代理模式)
- Idelegate.java 委托的任务
public interface Idelegate {
public abstract void doing();
}
- 有A可以执行委托的任务
public class ExecutorA implements Idelegate {
@Override
public void doing() {
System.out.println("ExecutorA.doing");
}
}
- 有B可以执行委托的任务
public class ExecutorB implements Idelegate {
@Override
public void doing() {
System.out.println("ExecutorB.doing");
}
}
- 委托人分配任务
public class Dispatcher implements Idelegate{
private Idelegate executor;
Dispatcher(Idelegate executor){
this.executor = executor;
}
@Override
public void doing() {
executor.doing();
}
}
Test:这里看似委托人做了任务,而实际上是B做了任务
public class TestDelegate {
public static void main(String[] args) {
Dispatcher dispatcher = new Dispatcher(new ExecutorB());
dispatcher.doing();
}
}
Output
ExecutorB.doing