一、命令模式介紹
1、定義與型別
定義:將“請求“封裝成物件,以便使用不同的請求
命令模式解決了應用程式中物件的職責以及它們之間的通信方式
型別:行為型
2、適用場景
請求呼叫者和請求接收者需要解耦,使得呼叫者和接收者不直接互動
需要抽象出等待執行的行為
3、優點
降低耦合
容易擴展新命令或者一組命令
4、缺點
命令的無限擴展會增加類的數量,提高系統實作復雜度
5、相關設計模式
命令模式和備忘錄模式經常相互結合,例如保存命令的歷史記錄
二、代碼示例
模擬場景:對課程視頻下達開放或者關閉的命令
課程視頻類:
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> commandList = new ArrayList<Command>();
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("命令模式課程");
Command openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo);
Command closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo);
Staff staff = new Staff();
staff.addCommand(openCourseVideoCommand);
staff.addCommand(closeCourseVideoCommand);
staff.executeCommands();
}
}
輸出:
命令模式課程課程視頻開放
命令模式課程課程視頻關閉
三、原始碼示例
1、JDK中的Runnable
可理解為抽象的命令,實作Runnable后可理解為具體的執行的命令

2、junit中的Test

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/4537.html
標籤:設計模式
上一篇:備忘錄模式
下一篇:設計模式(1) 工廠方法模式
