定义
- 将"请求"封装成对象,以便使用不同的请求
- 命令模式解决了应用程序中对象的职责以及它们之间的通信方式
类型
行为型
适用场景
- 请求调用者和请求接收者需要解耦,使得调用者和接收者不直接交互
- 需要抽象出等待执行的行为
优点
- 降低耦合
- 容易扩展新命令或者一组命令
缺点
命令的无限扩展会增加类的数量,提高系统实现复杂度
Coding
引入一个场景:某视频网站视频课程,关闭视频,公开视频。
视频课程类:
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> commands = new ArrayList<>();
public void addCommand(Command command){
this.commands.add(command);
}
public void executeCommands(){
for (Command command : this.commands) {
command.execute();
}
this.commands.clear();
}
}
最后看客户端调用:
public class Test {
public static void main(String[] args) {
CourseVideo video = new CourseVideo("java设计模式精讲");
OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(video);
CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(video);
Staff staff = new Staff();
staff.addCommand(openCourseVideoCommand);
staff.addCommand(closeCourseVideoCommand);
staff.executeCommands();
}
}
如果帮到你了,请点击右上角给个赞吧!!
学习笔记。内容总结于Geely老师的《Java设计模式精讲 》
欢迎访问我的博客: 他和她的猫