
public class Test {
public static void main(String[] args) {
King king = new King();
Slave slave = new Slave();
king.order(slave);
}
}
interface Command {
void execute();
void undo();
}
class CookCommand implements Command {
public void execute() {
System.out.println("cook...");
}
public void undo() {
System.out.println("undo cook...");
}
}
class WashCommand implements Command{
public void execute() {
System.out.println("wash...");
}
public void undo() {
System.out.println("undo wash...");
}
}
class Slave { // 命令执行者。持有多个命令的引用。
private List<Command> commands = new ArrayList<Command>();
public void add(Command c) {
commands.add(c);
}
public void execute () {
for (Iterator<Command> iter = commands.iterator(); iter.hasNext();) {
iter.next().execute();
}
}
public void undo() {
for (Iterator<Command> iter = commands.iterator(); iter.hasNext();) {
iter.next().undo();
}
}
}
class King {
public void order (Slave s) { // 这个方法充当客户端代码
Command cook = new CookCommand();
s.add(cook);
Command wash = new WashCommand();
s.add(wash);
s.execute();
}
}
本文介绍了一种常用的设计模式——命令模式,并通过一个简单的Java实现案例进行说明。该案例展示了如何利用命令模式解耦请求发送者与接收者,使得发送者与接收者之间不需要直接交互。
1872

被折叠的 条评论
为什么被折叠?



