目录
一.什么是委派模式
委派模式(Delegate Pattern)又叫委托模式。它的基本作用就是负责任务的调度和任务分配,将任务的分配和执行分离开来。可以看做是一种特殊情况下的静态代理的全权代理。
不属于GOF 23种设计模式之一。
属于行为型模式。
委派模式的优点:
通过任务委派能够将一个大型的任务细化,然后通过统一管理这些子任务的完成情况实现任务的跟进,能够加快任务执行的效率。
委派模式的缺点:
任务委派方式需要根据任务的复杂程度进行不同的改变,在任务比较复杂的情况下可能需要进行多重委派,容易造成紊乱。
委派模式的应用场景:
- 委派对象本身不知道如何处理一个任务(或一个请求),把请求交给其它对象来处理。
- 实现程序的解耦。
委派模式和代理模式的区别:
- 委派模式是行为型模式,代理模式是结构型模式
- 委派是我让你做,代理是我帮你做
- 委派模式注重的是任务派遣,注重结果;代理模式注重的是代码增强,注重过程。
- 委派模式是一种特殊的静态代理,相当于全权代理。
- 静态代理模式会在执行过程中在前面或者后面增加一些逻辑,而委派只是负责调用(就是把任务委派给别的对象做)
二.代码演示
首先我们先设想一个场景: 老师需要找两个同学帮忙"搬桌子" 和"画海报",但是大学的老师可能连班级里的学生姓名都叫不全,所以她并不知道同学们谁擅长画海报和搬桌子,这时候他就把任务交给了班长,班长就会把搬桌子这种力气活委派给经常健身的学生A,把画海报委派给擅长平面设计的学生B.
类图:
IStudent
public interface IStudent {
void doing(String task);
}
StudentA
public class StudentA implements IStudent{
private String goodAt = "健身";
@Override
public void doing(String task) {
System.out.println("我是学生A,我擅长" + goodAt + ";现在我在" + task);
}
}
StudentB
public class StudentB implements IStudent{
private String goodAt = "平面设计";
@Override
public void doing(String task) {
System.out.println("我是学生B,我擅长" + goodAt + ";现在我在" + task);
}
}
Monitor
public class Monitor implements IStudent{
private Map<String, IStudent> studentMap = new ConcurrentHashMap<String, IStudent>();
public Monitor() {
//加入一些简单的策略
studentMap.put("搬桌子", new StudentA());
studentMap.put("画海报", new StudentB());
}
@Override
public void doing(String task) {
if (studentMap.containsKey(task)) {
studentMap.get(task).doing(task);
} else {
System.out.println("这个任务:" + task + "超出我的能力范围!");
}
}
}
Teacher
public class Teacher {
public void allocating(String task, Monitor monitor) {
monitor.doing(task);
}
}
Test
public class Test1 {
public static void main(String[] args) {
new Teacher().allocating("搬桌子", new Monitor());
new Teacher().allocating("画海报", new Monitor());
}
}