/** * 命令接口類 */ public interface Command { void executor(); } /** * 命令1 */ public class ConcreteCommand1 implements Command { private Receiver receiver; public ConcreteCommand1(Receiver receiver) { this.receiver = receiver; } @Override public void executor() { receiver.action("concrete command 1."); } } /** * 命令2 */ public class ConcreteCommand2 implements Command { private Receiver receiver; public ConcreteCommand2(Receiver receiver) { this.receiver = receiver; } @Override public void executor() { receiver.action("concrete command 2."); } } /** * 命令執行人 */ public class Invoker { private List<Command> commands = new ArrayList<>(); public void addCommand(Command command) { commands.add(command); } public void executorCommands() { commands.forEach(Command::executor); commands.clear(); } } /** * 命令接收者 */ public class Receiver { public void action(String name) { System.out.println(name); } }
/** * 應用與測試 */ public class Test { public static void main(String[] args) { //建立命令接收方 Receiver receiver = new Receiver(); //建立執行者 Invoker invoker = new Invoker(); //建立命令 ConcreteCommand1 concreteCommand1 = new ConcreteCommand1(receiver); ConcreteCommand2 concreteCommand2 = new ConcreteCommand2(receiver); //添加命令 invoker.addCommand(concreteCommand1); invoker.addCommand(concreteCommand2); //執行 invoker.executorCommands(); } }
concrete command 1. concrete command 2.
命令模式角色介紹html
/** * 命令接口 */ public interface Command { void execute(); } /** * 打開課程連接 */ public class OpenCourseVideoCommand implements Command { private CourseVideo courseVideo; public OpenCourseVideoCommand(CourseVideo courseVideo) { this.courseVideo = courseVideo; } @Override public void execute() { courseVideo.open(); } } /** * 關閉課程連接 */ public class CloseCourseVideoCommand implements Command { private CourseVideo courseVideo; public CloseCourseVideoCommand(CourseVideo courseVideo) { this.courseVideo = courseVideo; } @Override public void execute() { courseVideo.close(); } } /** * 命令接受類 */ public class CourseVideo { private String name; public CourseVideo(String name) { this.name = name; } public void open () { System.out.println(this.name + "課程視頻開放。"); } public void close () { System.out.println(this.name + "課程視頻關閉。"); } } /** * 執行人 */ public class Staff { private List<Command> commands = new ArrayList<>(); public void addCommand (Command command) { commands.add(command); } public void executeCommands () { commands.forEach(Command::execute); commands.clear(); } }
/** * 測試與應用 */ public class Test { public static void main(String[] args) { //命令接收者 CourseVideo courseVideo = new CourseVideo("Java設計模式精講"); //建立命令 OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo); CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo); //建立執行人 Staff staff = new Staff(); //添加命令 staff.addCommand(openCourseVideoCommand); staff.addCommand(closeCourseVideoCommand); //執行 staff.executeCommands(); } }
命令模式和備忘錄模式java