命令模式--代码类图,man看了会沉默

命令模式

定义:

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

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

类型:

行为型

适用场景:

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

需要抽象出等待执行的行为。

优点:

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

缺点:

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

命令模式VS备忘录模式

备忘录模式可以保存命令历史记录。

代码:
//被命令操作的类CourseVideo
public class CourseVideo {
    private String name;

    public CourseVideo(String name) {
        this.name = name;
    }
    public void open(){
        System.out.println(name+"开放");
    }
    public void close(){
        System.out.println(name+"关闭");
    }
}

//命令接口Command
public interface Command {
    void execute();
}

//命令实现类OpenCourseVideoCommand
public class OpenCourseVideoCommand implements Command {
    private CourseVideo courseVideo;

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

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

    }
}

//命令实现类CloseCourseVideoCommand
public class CloseCourseVideoCommand implements Command {
    private CourseVideo courseVideo;

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

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

//命令执行类Staff
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();
    }
}

//测试类
public class Test {
    public static void main(String[] args) {
        //声明课程
        CourseVideo courseVideo=new CourseVideo("java&python");
        //声明命令对象
        OpenCourseVideoCommand openCourseVideoCommand=new OpenCourseVideoCommand(courseVideo);
        CloseCourseVideoCommand closeCourseVideoCommand=new CloseCourseVideoCommand(courseVideo);

        //给员工下命令
        Staff staff=new Staff();
        staff.addCommand(openCourseVideoCommand);
        staff.addCommand(closeCourseVideoCommand);
        //员工执行命令
        staff.executeCommands();
    }
}

类图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-thXyYPw6-1606557183534)(G:\研究生课程\第一学期\高级软件设计\photo\08 命令模式\Package command.png)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值