我正在尝试实现一种策略模式但不确定如何将策略接口作为 通用的。
请参阅下面的示例代码:
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
{
}
但是你可以看到ISerializerStrategy
对PatientDto
非常具体。如何使这个界面抽象或通用,这也适用于
PrescriberDtoSerializerStrategy
?
有人可以向我推荐吗?
答案 0 :(得分: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>();