委派模式的定义
委派模式(Delegate Pattern)的基本作用就是负责任务的调度和分配任务,跟代理模式很像,可以看做是一种特殊情况下的静态代理的全权代理,但是代理模式注重过程,而委派模式则注重结果。
委派模式不属于GOF23种设计模式之一,它属于行为型模式。
在Spring中一般以Delegate, 或者 Dispatcher结尾的都是委派模式。
委派模式的作用
委派模式可以精简程序逻辑,提升代码的可读性和优雅性。
委派模式简单示例
public class Boss {
/**
* 老板只会下命令
*/
public void command(String command, Leader leader){
leader.doSomething(command);
}
}
public class Leader {
private Map<String,IEmployee> map = new HashMap<String,IEmployee>();
/**
* 初始化
*/
public Leader(){
map.put("搭框架", new EmployeeA());
map.put("写代码", new EmployeeB());
}
public void doSomething(String command){
map.get(command).doSomething(command);
}
}
public interface IEmployee {
void doSomething(String command);
}
public class EmployeeA implements IEmployee {
@Override
public void doSomething(String command){
System.out.println("我是员工A, 我负责:"+command);
}
}
public class EmployeeB implements IEmployee {
@Override
public void doSomething(String command){
System.out.println("我是员工B, 我负责:"+command);
}
}
public class DelegateSimpleTest {
public static void main(String[] args) {
new Boss().command("搭框架",new Leader());
new Boss().command("写代码",new Leader());
}
}
源码中的运用
org.springframework.beans.factory.xml.BeanDefinitionParserDelegate