命令模式

一、定义

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

命令模式解决了应用程序中对象的职责以及它们之间的通信方式。(发送者和接收者完全解耦)

类型:行为型

二、适用场景

1、请求调用者和请求接收者需要解耦,使得调用者和接收者不直接交互。

2、需要抽象出等待执行的行为

三、优点

1、降低耦合

2、容易扩展新命令或者一组命令

四、缺点

1、命令的无限扩展会增加类的数量,提高系统实现复杂度

五、命令模式-相关设计模式

1、命令模式和备忘录模式

两者可以结合起来,例如备忘录模式可以保存命令的历史记录。

六、Coding

 场景:通过命令关闭课程某一部分或者某一小节

 1、Command 接口

public interface Command {
    void execute();
}

  

2、CourseVideo 类

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 +"课程视频关闭");
    }
}

  

3、OpenCourseVideoComand 打开课程权限为免费命令

public class OpenCourseVideoComand implements  Command{

    private CourseVideo courseVideo;

    public OpenCourseVideoComand(CourseVideo courseVideo) {
        this.courseVideo = courseVideo;
    }

    @Override
    public void execute() {
        this.courseVideo.open();
    }
}

  

4、CloseCourseVideoCommand 关闭课程权限为免费命令

public class CloseCourseVideoCommand implements  Command{

    public CourseVideo courseVideo;

    public CloseCourseVideoCommand(CourseVideo courseVideo) {
        this.courseVideo = courseVideo;
    }

    @Override
    public void execute() {
        this.courseVideo.close();
    }
}

  

5、员工类

/**
 * 员工类
 */
public class Staff {
    private List<Command> commandList = new ArrayList<>();
    public void addCommand(Command command){
        commandList.add(command);
    }

    public void executeCommands(){
        for(Command command: commandList){
            command.execute();
        }
        commandList.clear();
    }
}

  

6、UML图

7、测试

public class Test {
    public static void main(String[] args) {
        CourseVideo courseVideo = new CourseVideo("Java设计模式");
        OpenCourseVideoComand openCourseVideoComand = new OpenCourseVideoComand(courseVideo);
        CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo);

        Staff staff = new Staff();
        //老板下命令:开发视频课程
        staff.addCommand(openCourseVideoComand);
        //老板下命令:关闭视频课程
        staff.addCommand(closeCourseVideoCommand);
        staff.executeCommands();

    }
}

  结果:

Java设计模式课程视频开放
Java设计模式课程视频关闭

  

八、命令模式在源码中的应用

1、Runnable 

可以理解为抽象的命令

 Runnable的实现,可以理解为具体实现的命令。

2、junit.framework下的Test接口

run方法,可以理解为命令模式的execute方法。

原文地址:https://www.cnblogs.com/linlf03/p/10460752.html