命令模式
1.定义:将“请求”封装成对象,以便使用不同的请求;
命令模式解决了应用程序中对象的职责以及它们之间的通信方式。
2.类型:行为型
3.适用场景:请求调用者和请求接收者需要解耦,使得调用者和接收者不直接交互;
需要抽象出等待执行的行为。
4.优点:降低耦合,容易扩展新命令或者一组命令。
5.缺点:命令的无限扩展会增加类的数量,提高系统实现复杂度。
6.相关设计模式:备忘录模式
7.实例目录package
8.实例UML类图
9.代码
1 package com.geely.design.pattern.behavioral.command; 2 3 public class CourseVideo { 4 private String name; 5 6 public CourseVideo(String name) { 7 this.name = name; 8 } 9 public void open(){ 10 System.out.println(this.name + "课程视频开发"); 11 } 12 public void close(){ 13 System.out.println(this.name + "课程视频关闭"); 14 } 15 }
1 package com.geely.design.pattern.behavioral.command; 2 3 public interface Command { 4 void execute(); 5 }
1 package com.geely.design.pattern.behavioral.command; 2 3 public class CloseCourseVideoCommand implements Command { 4 private CourseVideo courseVideo; 5 6 public CloseCourseVideoCommand(CourseVideo courseVideo) { 7 this.courseVideo = courseVideo; 8 } 9 10 @Override 11 public void execute() { 12 courseVideo.close(); 13 } 14 }
1 package com.geely.design.pattern.behavioral.command; 2 3 public class OpenCourseVideoCommand implements Command { 4 private CourseVideo courseVideo; 5 6 public OpenCourseVideoCommand(CourseVideo courseVideo){ 7 this.courseVideo = courseVideo; 8 } 9 10 @Override 11 public void execute() { 12 courseVideo.open(); 13 } 14 }
1 package com.geely.design.pattern.behavioral.command; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class Staff { 7 private List<Command> commandList = new ArrayList<>(); 8 9 public void addCommand(Command command){ 10 commandList.add(command); 11 } 12 13 public void executeCommands(){ 14 for(Command command : commandList){ 15 command.execute(); 16 } 17 commandList.clear(); 18 } 19 }
1 package com.geely.design.pattern.behavioral.command; 2 3 public class Test { 4 public static void main(String[] args) { 5 CourseVideo courseVideo = new CourseVideo("Java设计模式精讲 -- By Geely"); 6 OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo); 7 CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo); 8 9 Staff staff = new Staff(); 10 staff.addCommand(openCourseVideoCommand); 11 staff.addCommand(closeCourseVideoCommand); 12 13 staff.executeCommands(); 14 } 15 }