【设计模式】17.行为型模式-命令(Command)
一、描述
将一个请求封装为一个对象,使请求者和接收者分离开来,实现解耦。可以提供命令的撤销和恢复功能。
角色:
1.请求者:发出请求,调用命令。
2.抽象命令类:定义抽象接口。
3.具体命令类:实现抽象命令类中的抽象接口,将命令发送给接收者。
4.接收者:接收命令,并且做出相关操作。
类图:
二、优点
1.将请求者与接收者解耦,降低耦合度。请求者不需要知道接受者如何执行命令。
2.命令类可以用于各种各样对象,不局限于限定对象。
三、缺点
1.结构繁琐,每个命令都需要加命令类。
四、适用场景
1.系统需要将请求者与接收者解耦,使得调用者和接受者不直接交互。
2.系统需要在不同的时间指定请求、将请求排队和执行请求
3.系统需要支持命令的撤销操作和恢复操作。
4.系统需要将一组操作组合在一起,即支持宏命令。
五、举例
以“开关空调”为例:用户使用遥控器开空调制冷、制热或者关闭空调。类图如下:
代码如下:
1.接收类:冰箱
public class Refrigerator { public void doRefrigeration(){ System.out.println("3.开始制冷。。。。"); } public void heating(){ System.out.println("3.开始制热。。。。"); } public void close(){ System.out.println("3.关闭空调。。。。"); } }
2.抽象命令类
public interface AbstractCommand { void execute(); }
3.制冷命令类:
public class RefrigerationCommand implements AbstractCommand { private Refrigerator refrigerator; public void setRefrigerator(Refrigerator refrigerator) { this.refrigerator = refrigerator; } @Override public void execute() { System.out.println("2.接收制冷请求"); refrigerator.doRefrigeration(); } }
4.制热命令类:
public class HeatingCommand implements AbstractCommand { private Refrigerator refrigerator; public void setRefrigerator(Refrigerator refrigerator) { this.refrigerator = refrigerator; } @Override public void execute() { System.out.println("2.接收制冷请求"); refrigerator.heating(); } }
5.关闭空调类:
public class CloseCommand implements AbstractCommand { private Refrigerator refrigerator; public void setRefrigerator(Refrigerator refrigerator) { this.refrigerator = refrigerator; } @Override public void execute() { System.out.println("2.接收关闭请求"); refrigerator.close(); } }
6.调用者:使用者
public class User { private AbstractCommand command; public void setCommand(AbstractCommand command) { this.command = command; } public void doAction() { System.out.println("1.调用命令"); command.execute(); } }
7.测试类:
public class Client { public static void main(String[] args) { Refrigerator refrigerator = new Refrigerator(); RefrigerationCommand refrigerationCommand = new RefrigerationCommand(); refrigerationCommand.setRefrigerator(refrigerator); User user = new User(); user.setCommand(refrigerationCommand); user.doAction(); System.out.println("\n"); CloseCommand closeCommand = new CloseCommand(); closeCommand.setRefrigerator(refrigerator); user.setCommand(closeCommand); user.doAction(); } }
实现效果:
1.调用命令 2.接收制冷请求 3.开始制冷。。。。 1.调用命令 2.接收关闭请求 3.关闭空调。。。。