示例类图
示例代码
抽象命令
- 新定义的接口,用于调用系统中现成的类;
public interface Command {
void execute();
}
具体命令
- 新创建的实现了新接口的类,其中组合了系统中现成的类,从而可以用新接口调用系统中现成的类;
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 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 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("Java设计模式精讲 -- By Geely");
OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo);
CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo);
Staff staff = new Staff();
staff.addCommand(openCourseVideoCommand);
staff.addCommand(closeCourseVideoCommand);
staff.executeCommands();
}
}
输出:
Java设计模式精讲 -- By Geely课程视频开放
Java设计模式精讲 -- By Geely课程视频关闭