• 命令模式


    一、命令模式介绍

    1、定义与类型

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

    2、适用场景

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

    3、优点

    降低耦合
    容易扩展新命令或者一组命令

    4、缺点

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

    5、相关设计模式

    命令模式和备忘录模式经常相互结合,例如保存命令的历史记录

    二、代码示例

    模拟场景:对课程视频下达开放或者关闭的命令

    课程视频类:

    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 interface Command {
        void execute();
    }
    

    开放命令类:

    public class OpenCourseVideoCommand implements Command{
    
        private CourseVideo courseVideo;
    
        public OpenCourseVideoCommand(CourseVideo courseVideo) {
            this.courseVideo = courseVideo;
        }
    
        @Override
        public void execute() {
            this.courseVideo.open();
        }
    }
    

    关闭命令类:

    public class CloseCourseVideoCommand implements Command{
    
        private CourseVideo courseVideo;
    
        public CloseCourseVideoCommand(CourseVideo courseVideo) {
            this.courseVideo = courseVideo;
        }
    
        @Override
        public void execute() {
            this.courseVideo.close();
        }
    }
    

    调用命令的类:

    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();
        }
    }
    

    测试类:

    public class Test {
        public static void main(String[] args) {
            CourseVideo courseVideo = new CourseVideo("命令模式课程");
    
            Command openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo);
            Command closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo);
    
            Staff staff = new Staff();
            staff.addCommand(openCourseVideoCommand);
            staff.addCommand(closeCourseVideoCommand);
    
            staff.executeCommands();
        }
    }
    

    输出:
    命令模式课程课程视频开放
    命令模式课程课程视频关闭

    三、源码示例

    1、JDK中的Runnable

    可理解为抽象的命令,实现Runnable后可理解为具体的执行的命令

    2、junit中的Test

  • 相关阅读:
    sql server 如何查看这个数据库有多少张表并具体显示出来
    SQL Server2008 SP1安装 查找安装媒体怎么解决
    检测到在集成的托管管道模式下不适用的 ASP.NET 设置。
    sql不记得用户名跟密码怎么办
    必背系列之数据库常用语法
    select * from 多张表的用法
    SAP与Oracle ERP
    with as的用法
    IIS启动网站--HTTP错误500.21
    SqlServer2012--备份介质集不完整 ,介质集有2个介质簇但只提供了1个
  • 原文地址:https://www.cnblogs.com/weixk/p/13222868.html
Copyright © 2020-2023  润新知