命令模式

定义:将“请求”封装成对象,以便使用不同的请求,命令模式解决了应用程序中对象的职责以及他们之间的通信方式;
类型:行为型;

适用场景:
  1. 请求调用者和请求接收者需要接耦,使得使用者和接收者不直接交互;
  2. 需要抽象出等待执行的行为;
优点:
  1. 降低耦合;
  2. 容易扩展新命令或者一组命令;
缺点:
  1. 命令的无限扩展会增加类的数量,提高系统实现复杂度;
课程命令举例:
// 课程类
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课程课程关闭
测试用例类图:

在这里插入图片描述

源码分析:
  1. 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();
}
  1. junit.framework包下的Test接口
public interface Test {
    int countTestCases();

    void run(TestResult var1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值