2017-05-07 63 views
1

我看不到任何命令模式類,例如調用者,接收者在以下鏈接的接受答案中出現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。

接受的答案是否表示命令模式的一種(近似)實現?

回答

0

它看起來像一個枚舉,實現一個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. 

你想要哪個上面的呢?

+0

我會選擇第一個選項,它不是一個命令模式,有些答案是如此具有誤導性,但是,我也會使用模式中的一些想法,但不會將它們稱爲模式。 –

+0

也許就像https://industriallogic.com/xp/refactoring/conditionDispatcherWithCommand.html –