一.定义与类型
1.定义:将“请求”封装成对象,以便使用不同的请求
命令模式解决了应用程序中对象的职责以及它们之间的通信方式
2.类型:行为型
二.适用场景
1.请求调用者和请求接收者需要解耦,使得调用者和接收者不直接交互
2.需要抽象出等待执行的行为
三.优点
1.降低耦合
2.容易扩展新命令或者一组命令
四.缺点
1.命令的无限扩展会增加类的数量,提高系统实现复杂度
五.UML类图
六.代码
Command.java
package com.caomingyu.autotest.command;
public interface Command {
void excute();
}
CourseVideo.java
package com.caomingyu.autotest.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 + "课程视频关闭");
}
}
CloseCourseVideoCommand.java
package com.caomingyu.autotest.command;
public class CloseCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public CloseCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
public void excute() {
courseVideo.close();
}
}
OpenCourseVideoCommand.java
package com.caomingyu.autotest.command;
public class OpenCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public OpenCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
public void excute() {
courseVideo.open();
}
}
Staff.java
package com.caomingyu.autotest.command;
import java.util.ArrayList;
import java.util.List;
public class Staff {
private List<Command> commandList = new ArrayList<Command>();
public void addCommand(Command command){
commandList.add(command);
}
public void executeCommands(){
for (Command command: commandList){
command.excute();
}
commandList.clear();
}
}
Test.java
package com.caomingyu.autotest.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();
}
}