设计模式之---命令模式

in #steemit7 years ago


命令模式(Command Pattern)

定义

Encapsulate arequest as an object, thereby letting you parameterize clientswith different requests, queue or log requests, and support un-doable operations.
将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
类图:略
我们可以看到命令模式主要设计三个功能类

  • 接收者类 Receive
  • 命令类 Command
  • 调用者类 Invoker

优点

  • 类间解耦
  • 可扩展性

缺点

  • 命令类过多会导致项目可维护性降低
    代码
public abstract class Reveiver {
    public abstract void doSomething();
}
public class ConcreteReceiver1 extends Reveiver{
    public void doSomething() {
        System.out.println("ConcreteReceiver1");
  }
}
public class ConcreteReceiver2  extends Reveiver{
    public void doSomething() {
        System.out.println("ConcreteReceiver2");
  }
}
public  abstract  class Command {
    public abstract void execute();
}
public class ConcreteCommand1 extends Command {
    private Reveiver reveiver;
 public ConcreteCommand1(Reveiver reveiver){
       this.reveiver=reveiver;

  }

    public void execute() {
        System.out.println("ConcreteCommand1");
  reveiver.doSomething();
  }
}
public class ConcreteCommand2 extends Command {
    private Reveiver reveiver;
 public ConcreteCommand2(Reveiver reveiver){
        this.reveiver=reveiver;

  }
    public void execute() {
        System.out.println("ConcreteCommand2");
  reveiver.doSomething();
  }
}
public class Invoker {
    private Command command;
 public void setCommand(Command command){
        this.command=command;
  }
    public void action(){
        this.command.execute();
  }
}

测试类

public class Test {
    public static void main(String[] args) {
        Invoker invoker = new Invoker();
  Reveiver reveiver = new ConcreteReceiver1();
  Command command = new ConcreteCommand1(reveiver);
  invoker.setCommand(command);
  invoker.action();
  }
}

执行结果

ConcreteCommand1
ConcreteReceiver1