第二十章 命令模式

快速导航
一、命令模式介绍
二、代码演示
三、jdk中使用命令模式的地方
一、 命令模式介绍

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

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

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

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

相关设计模式:
命令模式和备忘录模式

二、代码演示
/**
 * @program: adpn-pattern->CoursePPT
 * @description: 课程ppt
 * @author: Jstar
 * @create: 2019-12-01 17:34
 **/
public class CoursePPT {
    private String name;
    public CoursePPT(String name) {
        this.name = name;
    }
    public void open(){
        System.out.println(this.name+"打开");
    }
    public void close(){
        System.out.println(this.name+"关闭");
    }
}

/**
 * @program: adpn-pattern->Command
 * @description: 命令接口
 * @author: Jstar
 * @create: 2019-12-01 17:33
 **/
public interface Command {
    void execute();
}

/**
 * @program: adpn-pattern->OpenCommand
 * @description: 打开命令类
 * @author: Jstar
 * @create: 2019-12-01 17:37
 **/
public class OpenCommand implements Command{
    private CoursePPT coursePPT;
    public OpenCommand(CoursePPT coursePPT) {
        this.coursePPT = coursePPT;
    }
    @Override
    public void execute() {
        coursePPT.open();
    }
}

/**
 * @program: adpn-pattern->CloseCommand
 * @description: 关闭命令
 * @author: Jstar
 * @create: 2019-12-01 17:38
 **/
public class CloseCommand implements Command {
    private CoursePPT coursePPT;
    public CloseCommand(CoursePPT coursePPT) {
        this.coursePPT = coursePPT;
    }
    @Override
    public void execute() {
        coursePPT.close();
    }
}

// 测试类
public class Test {
    public static void main(String[] args) {
        CoursePPT ppt = new CoursePPT("golang课程 PPT");
        Command openCommand=new OpenCommand(ppt);
        Command closeCommand=new CloseCommand(ppt);
        openCommand.execute();
        closeCommand.execute();
    }
}

看一下类的uml图:
在这里插入图片描述

执行结果: 如预期一样

在这里插入图片描述

三、jdk中使用命令模式的地方

1、java.lang.Runnable

在这里插入图片描述
红框中的类都可以看做是 Runnable 的 实现命令。

2、junit.framework.Test

在这里插入图片描述
countTestCases(0 和 run() 都是命令模式。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值