委派模式不属于23种设计模式,在Spring中有许多运用,如Spring的子项目Spring MVC中的前端控制器DispatcherServlet就是委派模式的运用。
下面就以老板(Boss),领导(Leader),员工(Employee)为例。
/**
* @description:老板
*/
public class Boss {
public void command(String command,Leader leader) {
leader.doing(command);
}
}
/**
* @description:leader
*/
public class Leader {
private Map<String,IEmployee> feature = new HashMap<>();
public Leader(){
feature.put("TaskA",new EmployeeA());
feature.put("TaskB",new EmployeeB());
}
public void doing(String command) {
feature.get(command).doing(command);
}
}
public interface IEmployee {
void doing(String command);
}
``
```java
/**
* @description:EmployeeA
*/
public class EmployeeA implements IEmployee{
@Override
public void doing(String command) {
System.out.println("EmployeeA doing " + command);
}
}
```java
/**
* @description:EmployeeB
*/
public class EmployeeB implements IEmployee {
@Override
public void doing(String command) {
System.out.println("EmployeeB doing " + command);
}
}
/**
* @author :fenghua.gu
* @date :Created in 2019/10/9 9:38
* @description:DelegateTest
*/
public class DelegateTest {
public static void main(String[] args) {
Boss boss = new Boss();
boss.command("TaskA",new Leader());
boss.command("TaskB",new Leader());
}
}
测试结果