2016-12-13 6 views
1

私はある種類の戦略パターンを実装しようとしていますが、戦略インターフェースを というように汎用化する方法がわかりません。戦略パターンに関する設計上の問題

以下の私のサンプルコードを参照してください。

ここ
public interface ISerializer 
{ 
    XDocument Serialize(PharmacyProductDto presetDataDto); 
    XDocument Serialize(PatientDto presetDataDto); 
    PrescriberDto Deserialize(PrescriberDto xDocument); 
} 

    public class XmlSerializer : ISerializer 
    { 
    public XDocument Serialize(PharmacyProductDto presetDataDto) 
    { 
     return new XDocument(); 
    } 

    public XDocument Serialize(PatientDto presetDataDto) 
    { 
     return new XDocument(); 
    } 

    public PrescriberDto Deserialize(PrescriberDto xDocument) 
    { 
     return new PrescriberDto(); 
    } 
    } 

    public class PatientDto 
    { 
    } 

public class PrescriberDto 
{ 
} 

public class PharmacyProductDto 
{ 
} 

あなたはISerializerは基本的に異なるのDTOをシリアライズしていることがわかります。 XmlSerializerクラスは、多くの型をシリアル化するので、非常に面倒なものになります。また、今後いくつかのタイプを追加する予定です。

ここで戦略パターンを実装することを考えました。このような何か:

public interface ISerializerStrategy 
    { 
     XDocument Serialize(PatientDto presetDataDto); 
     PatientDto Deserialize(XDocument xDocument); 
    } 

public class PatientDtoSerializerStrategy : ISerializerStrategy 
{ 

} 

public class PrescriberDtoSerializerStrategy : ISerializerStrategy 
{ 

} 

しかし、あなたはISerializerStrategyPatientDtoに非常に具体的なであることがわかります。このインターフェイスを抽象的または汎用的にするにはどうすれば PrescriberDtoSerializerStrategyでも動作しますか?

誰かが私に提案できますか?

+0

は常にXMLにシリアライズシリアライズのでしょうか? – Nkosi

+0

@Nkosi:はい。私はマイケルの助けが私が探しているものだと思う。しかし、私の古い実装では、私はインターフェイスを注入するために使用するので、今ではジェネリックインターフェイスと私はそれを使用する方法がわからない –

答えて

4

は、一般的なインタフェースを使用します。

public interface ISerializerStrategy<T> 
{ 
    XDocument Serialize(T presetDataDto); 
    T Deserialize(XDocument xDocument); 
} 

public class PatientDtoSerializerStrategy : ISerializerStrategy<PatientDto> 
{ 
    XDocument Serialize(PatientDto presetDataDto); 
    PatientDto Deserialize(XDocument xDocument); 
} 

public class PrescriberDtoSerializerStrategy : ISerializerStrategy<PrescriberDto> 
{ 
    XDocument Serialize(PrescriberDto presetDataDto); 
    PrescriberDto Deserialize(XDocument xDocument); 
} 

使用

public class Foo 
{ 
    public Foo(ISerializerStrategy<PrescriberDto> serializer) 
    { 
     // ... 
    } 
} 

登録

container.RegisterType<ISerializerStrategy<PrescriberDto>, PrescriberDtoSerializerStrategy>(); 
+0

返信いただきありがとうございます。しかし、今私は別の問題に悩まされています。 古い実装では、ISerializerをユニティコンテナ経由で他のクラスに注入していました。 あなたのソリューションでは、インターフェイスは汎用のISerializerStrategy です。 どのように注入できますか? –

+0

このシナリオでは、 'ISerializerStrategy 'に依存する必要があります。もう1つの方法は、より汎用的なシリアライザを作成することです。インスピレーションのためのこの[fiddler](https://dotnetfiddle.net/0x4lax)の例を参照してください。 – Michael

関連する問題