作用

将“请求”封装成对象,以便使用不同的请求

解决应用程序中对象的职责以及它们之间的通信方式

请求调用者和接受者解耦

Demo设计

根据课程视频执行命令,比如播放 关闭

命令接口

只有一个执行方法

  1. public interface Command {
  2. void execute();
  3. }

用于被执行命令的实体类

课程视频类,提供两个方法视频开放,视频关闭,供命令类执行

  1. public class CourseVideo {
  2. private String name;
  3. public CourseVideo(String name) {
  4. this.name = name;
  5. }
  6. public void open() {
  7. System.out.println(this.name + "视频开放");
  8. }
  9. public void close() {
  10. System.out.println(this.name + "视频关闭");
  11. }
  12. }

命令实现类

根据课程视频创建两个类,都要实现命令接口

视频开放类

  1. public class OpenCourseVideoCommand implements Command {
  2. private CourseVideo courseVideo;
  3. public OpenCourseVideoCommand(CourseVideo courseVideo) {
  4. this.courseVideo = courseVideo;
  5. }
  6. @Override
  7. public void execute() {
  8. courseVideo.open();
  9. }
  10. }

视频关闭类

  1. public class CloseCourseVideoCommand implements Command {
  2. private CourseVideo courseVideo;
  3. public CloseCourseVideoCommand(CourseVideo courseVideo) {
  4. this.courseVideo = courseVideo;
  5. }
  6. @Override
  7. public void execute() {
  8. courseVideo.close();
  9. }
  10. }

管理命令类

用于保存命令,并根据存放命令的顺序来执行,实现命令接口的类都可以存放

  1. public class Staff {
  2. private List<Command> commands = new ArrayList<>();
  3. public void addCommand(Command command) {
  4. commands.add(command);
  5. }
  6. public void executeCommands() {
  7. commands.forEach(Command::execute);
  8. }
  9. }

测试

根据存放命令的顺序来执行

  1. public static void main(String[] args) {
  2. CourseVideo courseVideo = new CourseVideo("设计模式");
  3. OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo);
  4. CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo);
  5. Staff staff = new Staff();
  6. //存放命令
  7. staff.addCommand(openCourseVideoCommand);
  8. staff.addCommand(closeCourseVideoCommand);
  9. staff.addCommand(openCourseVideoCommand);
  10. staff.addCommand(closeCourseVideoCommand);
  11. //批量执行命令
  12. staff.executeCommands();
  13. }

image.png

小结

每新增一个命令就需要新建一个实现命令接口的类