十九 Java设计模式解析(命令模式)

2018-10-24  本文已影响0人  十丈_红尘
1️⃣概念

定义 : 将请求封装成对象以便使用不同的请求;命令模式解决了应用程序中对象的职责以及他们之间的通信方式;
类型 : 行为型


2️⃣适用场景

请求调用者和请求接收者需要解耦,使得调用者和接收者不直接交互;
需要抽象出等待执行的行为;


3️⃣优点

较低耦合
容易扩折新命令或者一组命令


4️⃣缺点

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


5️⃣命令模式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 创建OpenCourseVideoCommand类

public class OpenCourseVideoCommand implements Command {
    private CourseVideo courseVideo;

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

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

4 创建CloseCourseVideoCommand类

public class CloseCourseVideoCommand implements Command {
    private CourseVideo courseVideo;

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

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

5 声明Staff类

public class Staff {
    private List<Command> commandList = new ArrayList<Command>();
    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设计模式");
        OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo);
        CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo);

        Staff staff = new Staff();
        staff.addCommand(openCourseVideoCommand);
        staff.addCommand(closeCourseVideoCommand);

        staff.executeCommands();
    }
}

6️⃣命令模式源码解析

public interface Runnable

上一篇 下一篇

猜你喜欢

热点阅读