命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

    应用实例:struts 1 中的 action 核心控制器 ActionServlet 只有一个,相当于 Invoker,而模型层的类会随着不同的应用有不同的模型类,相当于具体的 Command。

    命令类

    1. /**
    2. * @author meikb
    3. * @desc
    4. * @date 2020-05-23 17:38
    5. */
    6. public abstract class Commond {
    7. public abstract void execute();
    8. }

    创建命令

    1. public class CreateCommond extends Commond{
    2. private Receiver receiver;
    3. public CreateCommond(Receiver receiver){
    4. this.receiver = receiver;
    5. }
    6. @Override
    7. public void execute() {
    8. this.receiver.user1();
    9. }
    10. }

    查看命令

    1. public class ViewCommond extends Commond{
    2. private Receiver receiver;
    3. public ViewCommond(Receiver receiver){
    4. this.receiver = receiver;
    5. }
    6. @Override
    7. public void execute() {
    8. this.receiver.user2();
    9. }
    10. }

    具体调用者

    1. public class Receiver {
    2. public void user1(){
    3. System.out.println("use1");
    4. }
    5. public void user2(){
    6. System.out.println("use2");
    7. }
    8. }

    命令持有者

    1. public class Invoker {
    2. private Commond commond;
    3. public Invoker(Commond commond){
    4. this.commond = commond;
    5. }
    6. public void call(){
    7. commond.execute();
    8. }
    9. }

    主函数

    1. public class CommondMain {
    2. public static void main(String[] args) {
    3. Receiver receiver = new Receiver();
    4. Commond createCommond = new CreateCommond(receiver);
    5. Commond viewCommond = new ViewCommond(receiver);
    6. Invoker invoker1 = new Invoker(createCommond);
    7. Invoker invoker2 = new Invoker(viewCommond);
    8. invoker1.call();
    9. invoker2.call();
    10. }
    11. }