本文共 2211 字,大约阅读时间需要 7 分钟。
命令模式是一种数据驱动的设计模式,属于行为型模式。它将操作请求以命令的形式包裹,并传递给目标对象。目标对象会寻找适合处理该命令的接收者,并将命令交给相应的接收者接收者执行命令。
通过将操作封装到命令对象中,可以实现以下功能:
命令模式主要包含以下四个角色:
以下是一个使用命令模式控制电灯开关的简单实现:
public interface Command { void execute();} public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.on(); }} public class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @override public void execute() { light.off(); }} public class Light { public void on() { System.out.println("灯是开启的"); } public void off() { System.out.println("灯是关闭的"); }} public class Invoker { private Command[] onCommands; private Command[] offCommands; private static final int SLOT_NUM = 7; public Invoker() { this.onCommands = new Command[SLOT_NUM]; this.offCommands = new Command[SLOT_NUM]; } public void setOnCommand(Command command, int slot) { onCommands[slot] = command; } public void setOffCommand(Command command, int slot) { offCommands[slot] = command; } public void onButtonPushed(int slot) { onCommands[slot].execute(); } public void offButtonPushed(int slot) { offCommands[slot].execute(); }} public class Client { public static void main(String[] args) { Invoker invoker = new Invoker(); Light light = new Light(); Command lightOnCommand = new LightOnCommand(light); Command lightOffCommand = new LightOffCommand(light); invoker.setOnCommand(lightOnCommand, 0); invoker.setOffCommand(lightOffCommand, 0); invoker.onButtonPushed(0); invoker.offButtonPushed(0); }} 在JDK中,可以使用以下工具进行命令模式的实现:
通过命令模式,可以实现对象之间的松耦合设计,便于扩展和维护多种操作行为。
转载地址:http://qdhiz.baihongyu.com/