且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我可以使用命令设计模式,我可以轻松地调用所需的方法?

更新时间:2022-06-16 23:30:01

命令模式是指令的执行者根本不需要知道什么是命令,它需要什么上下文信息或它所做的。所有这些都封装在命令中。

The main motivation for using the Command pattern is that the executor of the command does not need to know anything at all about what the command is, what context information it needs on or what it does. All of that is encapsulated in the command.

这样,您可以执行某些操作,例如按顺序执行的依赖于其他项目的命令列表,分配给某些触发事件等。

This allows you to do things such as have a list of commands that are executed in order, that are dependent on other items, that are assigned to some triggering event etc.

在你的例子中,你可以有其他类(例如空调)有自己的命令(例如 Turn Thermostat Up Turn Thermostat Down )。任何这些命令都可以分配给一个按钮,或者当满足某些条件时触发,而不需要任何知道该命令。

In your example, you could have other classes (e.g. Air Conditioner) that have their own commands (e.g. Turn Thermostat Up, Turn Thermostat Down). Any of these commands could be assigned to a button or triggered when some condition is met without requiring any knowledge of the command.

所以,总而言之,模式封装了所需的一切采取行动,并允许执行行动完全独立于任何上下文发生。如果这不是您的要求,那么该模式对您的问题空间可能没有帮助。

So, in summary, the pattern encapsulates everything required to take an action and allows the execution of the action to occur completely independently of any of that context. If that is not a requirement for you then the pattern is probably not helpful for your problem space.

以下是一个简单的用例:

Here's a simple use case:

interface Command {
    void execute();
}

class Light {
    public Command turnOn();
    public Command turnOff();
}

class AirConditioner {
    public Command setThermostat(Temperature temperature);
}

class Button {
    public Button(String text, Command onPush);
}

class Scheduler {
    public void addScheduledCommand(Time timeToExecute, Command command);
}

然后,您可以执行以下操作:

Then you can do things such as:

new Button("Turn on light", light.turnOn());
scheduler.addScheduledCommand(new Time("15:12:07"), airCon.setThermostat(27));
scheduler.addScheduledCommand(new Time("15:13:02"), light.turnOff());

正如您可以看到 Button Scheduler 根本不需要知道任何命令。 Scheduler 是一个可能包含命令集合的类的示例。

As you can see the Button and Scheduler don't need to know anything at all about the commands. Scheduler is an example of a class that might hold a collection of commands.

还要注意,在Java 8功能接口和方法引用使得这种类型的代码更加简洁:

Note also that in Java 8 functional interfaces and method references have made this type of code even neater:

@FunctionalInterface
interface Command {
    void execute();
}

public Light {
    public void turnOn();
}

new Button("Turn On Light", light::turnOn);   

现在转成命令的方法甚至不需要知道命令 - 只要他们具有正确的签名,您可以通过引用该方法静静地创建一个匿名命令对象。

Now the methods that are turned into commands don't even need to know about commands - as long as they have the correct signature you can quietly create a anonymous command object by referencing the method.