本设计模式资料源于慕课网,讲师:Geely 《Java设计模式精讲 Debug方式+内存分析》,本人作为自己手打整理作为学习的归纳总结。
一,模式介绍
1,定义和类型
- 定义:将“请求”封装成对象,以便使用不同的请求
- 命令模式解决了应用程序中的对象的职责以及他们之间的通信方式
- 类型:行为型
2,适用场景
- 请求调用者和请求接收者需要解耦,使得调用者和接收者不直接交互
- 需要抽象出等待执行的行为
3,优点
- 降低耦合
- 容易扩展新命令或者一组命令
4,缺点
- 命令的无限扩展会增加类的数量,提高系统实现复杂度
5,相关设计模式
- 命令模式和备忘录模式
二,代码演示
- 业务场景
实现视频章节的部分开放和关闭
视频类
package com.try1.design.behavioral.command;
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+"课程视频关闭");
}
}
命令类的接口
package com.try1.design.behavioral.command;
public interface Command {
void execute();
}
对接口的开放课程实现
package com.try1.design.behavioral.command;
public class OpenCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public OpenCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
@Override
public void execute() {
courseVideo.open();
}
}
对接口的关闭课程实现
package com.try1.design.behavioral.command;
public class CloseCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public CloseCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
@Override
public void execute() {
courseVideo.close();
}
}
管理者类
package com.try1.design.behavioral.command;
import java.util.ArrayList;
import java.util.List;
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();
}
}
测试类
package com.try1.design.behavioral.command;
public class Test {
public static void main(String[] args) {
CourseVideo courseVideo=new CourseVideo("Java设计模式");
OpenCourseVideoCommand openCourseVideoCommand=new OpenCourseVideoCommand(courseVideo);
CloseCourseVideoCommand closeCourseVideoCommand=new CloseCourseVideoCommand(courseVideo);
Staff staff=new Staff();
staff.addCommand(openCourseVideoCommand);
staff.addCommand(closeCourseVideoCommand);
staff.executeCommands();
}
}
运行截图
三,小结
- 命令模式实际上是对执行命令和命令的请求执行进行了分割,这一点有点类似于代理模式,但是两者面对的对象和范围不同