命令模式
定义:
将请求封装成对象,以便使用不同的请求。
命令模式解决了应用程序中对象的职责以及它们之间的通信方式。
类型:
行为型
适用场景:
请求的调用者和请求的接收者需要解耦,使得调用者和接收者不直接交互。
需要抽象出等待执行的行为。
优点:
降低耦合,容易扩展新命令或者一组命令。
缺点:
命令的无限扩展会增加类的数量,提高系统实现复杂度。
命令模式VS备忘录模式
备忘录模式可以保存命令历史记录。
代码:
//被命令操作的类CourseVideo
public class CourseVideo {
private String name;
public CourseVideo(String name) {
this.name = name;
}
public void open(){
System.out.println(name+"开放");
}
public void close(){
System.out.println(name+"关闭");
}
}
//命令接口Command
public interface Command {
void execute();
}
//命令实现类OpenCourseVideoCommand
public class OpenCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public OpenCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
@Override
public void execute() {
courseVideo.open();
}
}
//命令实现类CloseCourseVideoCommand
public class CloseCourseVideoCommand implements Command {
private CourseVideo courseVideo;
public CloseCourseVideoCommand(CourseVideo courseVideo) {
this.courseVideo = courseVideo;
}
@Override
public void execute() {
courseVideo.close();
}
}
//命令执行类Staff
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();
}
}
//测试类
public class Test {
public static void main(String[] args) {
//声明课程
CourseVideo courseVideo=new CourseVideo("java&python");
//声明命令对象
OpenCourseVideoCommand openCourseVideoCommand=new OpenCourseVideoCommand(courseVideo);
CloseCourseVideoCommand closeCourseVideoCommand=new CloseCourseVideoCommand(courseVideo);
//给员工下命令
Staff staff=new Staff();
staff.addCommand(openCourseVideoCommand);
staff.addCommand(closeCourseVideoCommand);
//员工执行命令
staff.executeCommands();
}
}