命令模式说明
问题描述:
我看不到任何命令模式类,例如调用者,接收者在以下链接的接受答案中出现Long list of if statements in Java。我已经接受了接受的答案来解决我的30+ if/else语句。命令模式说明
我有一个存储库,我试图通过DTOs保存到数据库。我希望存储库调用DTO的正确保存方法,以便在运行时检查实例类型。
这里是库
private Map<Class<?>, Command> commandMap;
public void setCommandMap(Map<Class<?>, Command> commandMap) {
this.commandMap = commandMap;
}
实施和将填充的CommandMap
commandMap.put(Address.class, new CommandAddress());
commandMap.put(Animal.class, new CommandAnimal());
commandMap.put(Client.class, new CommandClient());
终于可以节省
public void getValue(){
commandMap.get(these.get(0).getClass()).save();
}
使用该服务类中的方法的方法Repo注册了commandMap。
接受的答案是否表示命令模式的一种(近似)实现?
答
它看起来像一个枚举,实现一个exec接口将消除你的if/else问题或把它变成一个开关。
看起来你不需要命令patterm。
Gof说:
Use the Command pattern when you want to
parameterize objects by an action to perform, as MenuItem objects did above. You can express such parameterization in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later point. Commands are an object-oriented replacement for callbacks.
specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address space-independent way, then you can transfer a command object for the request to a different process and fulfill the request there.
support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.
support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes. Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.
structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.
你想要哪个上面的呢?
我会选择第一个选项,它不是一个命令模式,有些答案是如此具有误导性,但是,我也会使用模式中的一些想法,但不会将它们称为模式。 –
也许就像https://industriallogic.com/xp/refactoring/conditionDispatcherWithCommand.html –