一、概述
命令模式
二、代码
1.Client.java
public class Client { public void request(Server server){
server.addCommand(new TextCommand());
server.addCommand(new ImageCommand());
server.doSomething();
}
}
2.Server.java
public class Server { private List<Command> commands = new ArrayList<Command>(); public void doSomething() {
for(Command c : commands){
c.execute();
}
} public void addCommand(Command command) {
commands.add(command);
} }
3.Command.java
public abstract class Command { public abstract void execute();
public abstract void unDo(); }
4.TextCommand.java
public class TextCommand extends Command { @Override
public void execute() {
System.out.println("TextCommand...........");
} @Override
public void unDo() {
// 涉及到操作的历史记录
} }
5.ImageCommand.java
public class ImageCommand extends Command { @Override
public void execute() {
System.out.println("ImageCommand...........");
} @Override
public void unDo() {
// 涉及到操作的历史记录
} }
6.Test.java
public class Test { @org.junit.Test
public void test(){
Client c = new Client();
c.request(new Server());
} }
三、运行结果