我们引入一个业务场景:课程里面是有视频的,我们想要局部关闭某一个视频,或者是局部打开某一个视频,如第一章节是开放的,是可以免费看的,而其他章节的课程就是需要购买了之后才能观看的;现在,管理员决定把第二章节也免费观看,然后又过了一阵,把第三章节的视频给进行开放了;又过一阵,把第二章节给关闭了;就是这么一个业务场景;
有一个命令类:
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 CloseCourseVideoCommand implements Command { private CourseVideo courseVideo; public CloseCourseVideoCommand(CourseVideo courseVideo) { this.courseVideo = courseVideo; } @Override public void execute() { courseVideo.close(); }}
public class OpenCourseVideoCommand implements Command { private CourseVideo courseVideo; public OpenCourseVideoCommand(CourseVideo courseVideo) { this.courseVideo = courseVideo; } @Override public void execute() { courseVideo.open(); }}
还有一个添加命令的类:
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设计模式"); OpenCourseVideoCommand openCourseVideoCommand = new OpenCourseVideoCommand(courseVideo); CloseCourseVideoCommand closeCourseVideoCommand = new CloseCourseVideoCommand(courseVideo); Staff staff = new Staff(); staff.addCommand(openCourseVideoCommand); staff.addCommand(closeCourseVideoCommand); staff.executeCommands(); }}
测试结果如下:
Java设计模式课程开放
Java设计模式课程关闭
联系客服