2017-05-07 11 views
1

コマンドパターンクラスは表示されません。以下のリンクLong list of if statements in Javaの受け入れられた回答に明示された呼び出し元、受取人。私は30 + if/else文を解決するための受け入れられた答えに行ってきました。コマンドパターンの明確化

データベースに保存するDTOを渡そうとしているリポジトリが1つあります。リポジトリが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インターフェイスを実装しているenumのように思えますが、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のようです –