首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >命令模式澄清

命令模式澄清
EN

Stack Overflow用户
提问于 2017-05-07 00:21:27
回答 1查看 161关注 0票数 1

我看不到任何命令模式类,例如调用者,接收器在以下链接Java中if语句的长列表的接受答案中显化。我已经使用了公认的答案来解决我的30+ if/else语句。

我有一个存储库,我试图将DTO传递到数据库中。我希望存储库为DTO调用正确的保存方法,所以我在运行时检查实例类型。

这里是存储库中的实现

代码语言:javascript
复制
private Map<Class<?>, Command> commandMap;
public void setCommandMap(Map<Class<?>, Command> commandMap) {
    this.commandMap = commandMap;
}

和一种将填充commandMap的方法

代码语言:javascript
复制
    commandMap.put(Address.class, new CommandAddress());
    commandMap.put(Animal.class, new CommandAnimal());
    commandMap.put(Client.class, new CommandClient());  

最后,保存

代码语言:javascript
复制
public void getValue(){
    commandMap.get(these.get(0).getClass()).save();
}

使用Repo的服务类注册commandMap。

接受的答案是否表示命令模式的某种(近似)实现?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-07 05:04:16

看起来,实现exec接口的枚举将消除if/exec问题,或者将其转换为交换机。

看起来您不需要命令patterm。

戈夫说:

代码语言:javascript
复制
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.

以上哪一项你想做?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43826629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档