作用
将“请求”封装成对象,以便使用不同的请求
解决应用程序中对象的职责以及它们之间的通信方式
请求调用者和接受者解耦
Demo设计
根据课程视频执行命令,比如播放 关闭
命令接口
只有一个执行方法
public interface Command {
void execute();
}
用于被执行命令的实体类
课程视频类,提供两个方法视频开放,视频关闭,供命令类执行
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 class OpenCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public OpenCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
@Override
public void execute() {
courseVideo.open();
}
}
视频关闭类
public class CloseCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public CloseCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
@Override
public void execute() {
courseVideo.close();
}
}
管理命令类
用于保存命令,并根据存放命令的顺序来执行,实现命令接口的类都可以存放
public class Staff {
private List<Command> commands = new ArrayList<>();
public void addCommand(Command command) {
commands.add(command);
}
public void executeCommands() {
commands.forEach(Command::execute);
}
}
测试
根据存放命令的顺序来执行
public static void main(String[] args) {
CourseVideo courseVideo = new CourseVideo("设计模式");
OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo);
CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo);
Staff staff = new Staff();
//存放命令
staff.addCommand(openCourseVideoCommand);
staff.addCommand(closeCourseVideoCommand);
staff.addCommand(openCourseVideoCommand);
staff.addCommand(closeCourseVideoCommand);
//批量执行命令
staff.executeCommands();
}
小结
每新增一个命令就需要新建一个实现命令接口的类