通过封装请求的execute()方法以及撤销请求的undo()方法:
接受者: package DesignPatterns.CommandMode1; import java.lang.reflect.Array; import java.util.ArrayList; public class StringReceiver { public void printString(ArrayList<String> arrayList) { System.out.println("输出后"); for (int i=0;i<arrayList.size();i++) { System.out.println(arrayList.get(i)); } } public void cancelString(ArrayList<String> arrayList) { System.out.println("取消输出后"); for (int i=0;i<arrayList.size();i++) { System.out.println(arrayList.get(i)); } } } 命令接口: package DesignPatterns.CommandMode1; import java.util.ArrayList; public interface StringCommand { void execute(String name); void undo(String name); } 具体命令: package DesignPatterns.CommandMode1; import java.util.ArrayList; public class StringConcreteCommand implements StringCommand{ ArrayList<String> arrayList; StringReceiver stringReceiver; public StringConcreteCommand(StringReceiver stringReceiver) { this.arrayList=new ArrayList<>(); this.stringReceiver=stringReceiver; } @Override public void execute(String name) { arrayList.add(name); stringReceiver.printString(arrayList); } @Override public void undo(String name) { arrayList.remove(name); stringReceiver.cancelString(arrayList); } } 请求者: package DesignPatterns.CommandMode1; import DesignPatterns.CommandMode.Command; public class StringInvoker { StringCommand stringCommand; String name; public void setName(String name) { this.name = name; } public void setStringCommand(StringCommand stringCommand) { this.stringCommand=stringCommand; } public void executeStringCommand() { stringCommand.execute(name); } public void undoStringCommand() { stringCommand.undo(name); } } 测试类: package DesignPatterns.CommandMode1; public class Application { public static void main(String[] args) { StringReceiver stringReceiver=new StringReceiver(); StringCommand stringCommand=new StringConcreteCommand(stringReceiver); StringInvoker stringInvoker=new StringInvoker(); stringInvoker.setStringCommand(stringCommand); stringInvoker.setName("xujinfeng"); stringInvoker.executeStringCommand(); stringInvoker.undoStringCommand(); } }