定义:将“请求”封装成对象,以便使用不同的请求,命令模式解决了应用程序中对象的职责以及他们之间的通信方式;
类型:行为型;
适用场景:
- 请求调用者和请求接收者需要接耦,使得使用者和接收者不直接交互;
- 需要抽象出等待执行的行为;
优点:
- 降低耦合;
- 容易扩展新命令或者一组命令;
缺点:
- 命令的无限扩展会增加类的数量,提高系统实现复杂度;
课程命令举例:
// 课程类
public class Course {
private String name;
public Course(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 CourseOpenCommand implements Command {
private Course course;
public CourseOpenCommand(Course course) {
this.course = course;
}
public void execute() {
course.open();
}
}
// 关闭命令
public class CourseCloseCommand implements Command {
private Course course;
public CourseCloseCommand(Course course) {
this.course = course;
}
public void execute() {
course.close();
}
}
// 命令执行员工
public class Staff {
private List<Command> commands = new ArrayList<Command>();
public void addComand(Command command){
commands.add(command);
}
public void execute(){
for (Command command : commands) {
command.execute();
}
commands.clear();
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Course course = new Course("Java课程");
Command open = new CourseOpenCommand(course);
Command close = new CourseCloseCommand(course);
Staff staff = new Staff();
staff.addComand(open);
staff.addComand(close);
staff.execute();
}
}
// 输出结果
Java课程课程开课
Java课程课程关闭
测试用例类图:
源码分析:
- jdk中java.lang包下的Runnable接口
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
- junit.framework包下的Test接口
public interface Test {
int countTestCases();
void run(TestResult var1);
}