1

同じクライアントが使用する一連のオブジェクト タイプを作成する必要があります。ファクトリーパターンの適用を考えています。しかし、私はこのデザイン パターンに慣れていないので、何人かからアドバイスをもらいたいと思っています。

MessageTypeA、MessageTypeB、および MessageType C があります。各メッセージ タイプは、XML 形式または通常のプレーン テキストである可能性があります。各メッセージ タイプには、1 つ以上のバージョンも含まれる場合があります。例、

MessageType A in xml format version 1,
MessageType A in xml format version 2,
MessageType A in xml format version 3.

MessageType A in plain text format version 1,
MessageType A in plain text format version 2,
MessageType A in plain text format version 3.

MessageType B in xml format version 1,
MessageType B in xml format version 2,
MessageType B in xml format version 3.

MessageType B in plain text format version 1,
MessageType B in plain text format version 2,
MessageType B in plain text format version 3.

これらのオブジェクトの作成にファクトリ デザイン パターンを適用する方法を教えてください。

4

2 に答える 2

1

まず、「Factory」パターンはありません。既知のパターンはFactory Method Patternです。このパターンでは、Factory メソッドのインスタンスごとに 1 つのタイプのオブジェクトを作成できます。次に、抽象ベースの Factory メソッドを渡し、単一の createメソッドを呼び出して、それが作成するものをインスタンス化します。

必要なのは、まったく別の動物であるAbstract Factory パターンだと思います。この場合、各 Factory インスタンスは、相互に関連するオブジェクトのファミリを作成します。あなたの特定のケースでは、次のようにモデル化します(疑似コード):

// Base abstract Abstract Factory
abstract class MessageAF {
   MsgType createMessageTypeA();  
   MsgType createMessageTypeB();  
   MsgType createMessageTypeC();  
}

// concrete implementation
class XmlFormatVersion1AF extends MessageAF {
   MsgType createMessageTypeA();  
   MsgType createMessageTypeB();  
   MsgType createMessageTypeC();  
}

// concrete implementation
class XmlFormatVersion2AF extends MessageAF {
   MsgType createMessageTypeA();  
   MsgType createMessageTypeB();  
   MsgType createMessageTypeC();  
}

// concrete implementation
class PlainTextFormatVersion1AF extends MessageAF {
   MsgType createMessageTypeA();  
   MsgType createMessageTypeB();  
   MsgType createMessageTypeC();  
}

次に、コードベースでは、主にタイプに依存し、MessageAFそれぞれの場合に適切なインスタンス実装を渡します。たとえばPlainTextFormatVersion1AF、プレーン テキスト メッセージ バージョン 1 を作成します。

于 2012-12-10T10:41:24.097 に答える
1

上記の Factory Method 設計パターンと「Builder」パターンの両方に興味があるかもしれません。

Builder は、抽象的な記述を具体的な表現に変換する場合に役立ちます。通常の例は、Headline-level-1:「私は見出しです」、base-text:「私はコンテンツです。ここに数行が入ります」などの要素として記述できる構造化文書です。これは、HTML、RTF、PDF などのいくつかの具体的なレンダリングに変換できます...

あなたのメッセージが、Giovanni の回答で説明されている比較的単純なメッセージ ファミリよりもそのモデルに適している場合は、そのパターンの用途が見つかる可能性があります。実際、私の考えでは、彼のソリューションは Builder の単純化されたバージョンです。

于 2012-12-10T11:15:13.103 に答える