繁体   English   中英

与策略模式有关的设计问题

[英]design issue related to strategy pattern

我正在尝试实现一种策略模式,但不确定如何使策略接口具有通用性。

请在下面查看我的示例代码:

 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也有效?

有人可以建议我吗?

使用通用接口:

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>(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM