Java 经典设计模式-- 04.行为型模式
/**命令执行类接口**/
interface Employee {
void execute(String s);
}
/**命令类,策略者**/
public class Commander {
/**策略**/
String thought;
/**策略者手下的管理者**/
Employee manager;
/**初始化策略者**/
public Commander(String thought, Employee manager) {
this.thought = thought;
this.manager = manager;
}
/**发布策略**/
public void command() {
/**管理者执行策略,命令者并不知道管理者如何执行**/
manager.execute(thought);
}
}
/**命令执行类,管理者,实现执行类接口**/
class Manager implements Employee {
/**管理者手下的执行者**/
List<Employee> executors;
/**初始化管理者**/
public Manager(List<Employee> executors) {
this.executors = executors;
}
/**命令执行方法**/
@Override
public void execute(String thought) {
/**遍历执行者,执行具体方法**/
Iterator<Employee> iterator = executors.listIterator();
while(iterator.hasNext()) {
iterator.next().execute(thought);
iterator.remove();
}
/**根据自己的想法分配任务给不同的执行者**/
executeParticular(thought + "五彩黑");
executeParticular(thought + "Cms 后台") ;
executeParticular(thought + "压力测试");
}
/**细分任务方法**/
public void executeParticular(String myThought) {
if (myThought.indexOf("后台") != -1) {
new CodeExecutor().execute(myThought);
} else if (myThought.indexOf("压力") != -1) {
new TestExecutor().execute(myThought);
} else if (myThought.indexOf("五彩黑") != -1) {
new DesignExecutor().execute(myThought);
}
}
}
/**执行者抽象类,仅作为范型辅助类使用**/
abstract class Executor implements Employee {
}
/**程序员执行者类**/
class CodeExecutor extends Executor {
/**程序员具体执行逻辑**/
@Override
public void execute(String thought) {
System.out.println("我是程序员,我负责实现 " + thought + " 的逻辑");
}
}
/**设计执行者类**/
class DesignExecutor extends Executor {
/**设计具体执行逻辑**/
@Override
public void execute(String thought) {
System.out.println("我是设计,我负责设计 " + thought + " 的样式");
}
}
/**测试执行者类**/
class TestExecutor extends Executor {
/**测试具体执行逻辑**/
@Override
public void execute(String thought) {
System.out.println("我是测试,我负责测试 " + thought + " 的功能");
}
}
class CommandTest {
public static void main(String[] args) {
/**为部门添加执行者**/
List<Employee> executors = new ArrayList<>();
executors.add(new DesignExecutor());
executors.add(new CodeExecutor());
executors.add(new TestExecutor());
/**为部门添加管理者,以及建立他与执行者的关系**/
Employee manager = new Manager(executors);
/**为部门添加策略者,以及建立他与管理者的关系**/
Commander commander = new Commander("让猪飞", manager);
/**策略者发布策略**/
commander.command();
}
}