快速导航
一、命令模式介绍
二、代码演示
三、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() 都是命令模式。


被折叠的 条评论
为什么被折叠?



