在前面的章节中,咱们介绍了单例模式,它是建立型模式的一员。今天咱们来介绍一下命令模式,它是行为型模式的一员。java
首先,让咱们来思考下面的问题:ide
话说有一家遥控器公司,他想制做一款很牛逼的遥控器。这个遥控器能够控制家里全部的电器,为了简单一点,假设全部的用户家里只有电视机和电灯两种电器。那么若是是你,你会怎么实现这个遥控器呢?
因为电视机和电灯是两个不一样的厂商生产的产品,因此他们的打开方式是不同的。首先让咱们来看一看这两个类的定义:测试
Television.java:this
public class Television { public void open() { System.out.println("打开电视"); } public void close() { System.out.println("关闭电视"); } }
ElectricLight.java:spa
public class ElectricLight { public void on() { System.out.println("打开电灯"); } public void off() { System.out.println("关闭电灯"); } }
让咱们来看下下面的设计:设计
RemoteControl.java:3d
public class RemoteControl { private String product; public void setProduct(String product) { this.product = product; } public void execute() { switch (product) { case "Television": new Television().open(); break; case "ElectricLight": new ElectricLight().on(); break; default: } } }
这个遥控器太棒了,我能够用它来控制家里的电视机和电灯,不再用处处翻找遥控器了。要是它还能够控制洗衣机那就更棒了。那么若是再在遥控器里添加一个洗衣机须要怎么作,哦,太糟糕了,我还须要把遥控器拆开,而后把洗衣机的命令添加进去,好痛苦有么有,那么有么有一种设计能够不对遥控器进行更改,就能够添加其余的家电呢。这个时候命令模式就能够发挥它的做用了。code
定义:将请求封装成对象,从而可使用不一样的请求将客户参数化,使得请求发送者和请求接受者之间互相隔离。对象
类图:blog
上面涉及到的角色有4个:
首先,定义一个抽象命令类:
Command.java:
public interface Command { void execute(); }
而后,实现抽象命令类:
TelevisionCommand.java:
public class TelevisionCommand implements Command { private Television television = new Television(); @Override public void execute() { television.open(); } }
ElectricLightCommand.java:
public class ElectricLightCommand implements Command { private ElectricLight electricLight = new ElectricLight(); @Override public void execute() { electricLight.on(); } }
而后,实现一个遥控器:
RemoteControl.java:
public class RemoteControl { private Command command; public void execute() { command.execute(); } public void initCommand(Command command) { this.command = command; } }
测试类:
Custom.java:
public class Custom { public static void main(String ...args) { RemoteControl remoteControl = new RemoteControl(); remoteControl.initCommand(new TelevisionCommand()); remoteControl.execute(); remoteControl.initCommand(new ElectricLightCommand()); remoteControl.execute(); } }