在很多程序员的开发过程可能都不知不觉中用到了这种模式,比如在使用对象的多个方法时候,有methodA,methodB,methodC三个方法可供使用,方法使用者对三个方法是使用是随机组合的。代码如下:
public class RemoteControl {
public void action1() {
Plane plane = new Plane();
plane.methodA();
plane.methodB();
}
public void action2() {
Plane plane = new Plane();
plane.methodB();
plane.methodC();
}
}
代码中RemoteControl依赖着Plane类,如果这个时候methodB需要增加一个参数或者是action2也要使用methodA方法,是不是就要修改RemoteControl类了,命令模式其实就是取消这种强耦合。需要在RemoteControl和Plane之间增加一层Command。
举一个遥控器(RemoteControl)遥控飞机(Plane)的例子,我们需要在中间一层命令信号(Command)。
public class Plane {
public void up() {
System.out.println("Wing Up!");
System.out.println("Fly Up!");
}
public void down() {
System.out.println("Wing Down!");
System.out.println("Fly Down!");
}
}
public interface Command {
public void move();
}
public class UpCommand implements Command {
private Plane plane;
public UpCommand() {
this.plane = new Plane();
}
@Override
public void move() {
plane.up();
}
}
public class DownCommand implements Command {
private Plane plane;
public DownCommand() {
this.plane = new Plane();
}
@Override
public void move() {
plane.down();
}
}
public class RemoteControl {
private Command command;
public RemoteControl(Command command) {
this.command = command;
}
public void controlPlane() {
command.move();
}
}
上面代码中,由原来的RemoteControl直接操作飞机move,改为由RemoteCommand来操作。这的情况下,如果Plane的up方法过期并改为up2(),那么在RemoteCommand里面进行修改即可,完全不需要改动RemoteControl类。
新建一个Person类用于玩遥控飞机:
public class Person {
public static void main(String[] args) {
Command upCommand = new UpCommand();
RemoteControl control = new RemoteControl(upCommand);
control.controlPlane();
Command downCommand = new UpCommand();
control = new RemoteControl(downCommand);
control.controlPlane();
}
}
Person类中的操作就是先让飞机up,再让飞机down。
综合例子来讲命令模式的缺点,如果现在需要增加一个命令让飞机先上后下的合并操作,我们只能增加一个UpAndDownCommand类,继承Command接口。如果后面还有各式各样的命令呢,会造成命令类越来越多,系统也就主键变的复杂。