我有以下代码库:
public abstract class Business
{
public BusinessType BusinessType { get; set; }
}
public class BusinessA : Business
{
public string SpecialA { get; set; }
}
public class BusinessB : Business
{
public string SpecialB { get; set; }
}
实现该接口的通用接口和类:
public interface IBusinessMapper<T>
{
void DoMapping(T business);
}
public class BusinessMapperA : IBusinessMapper<BusinessA>
{
void DoMapping(BusinessA business)
{
//...
}
}
public class BusinessMapperB : IBusinessMapper<BusinessB>
{
void DoMapping(BusinessB business)
{
//...
}
}
现在我想创建一个类BusinessMapperA或BusinessMapperB的实例,具体取决于某些值。是否可以使用类似的东西?:
public class Core
{
public void Process(Business newBusiness)
{
var mapper = GetBusinessMapper(newBusiness.BusinessType);
mapper.DoMapping();
}
private IBusinessMapper<T> GetBusinessMapper(BusinessType businessType)
{
switch (businessType)
{
case BusinessType.A:
return new BusinessMapperA();
case BusinessType.B:
return new BusinessMapperB();
default:
throw new Exception("Not supported");
}
}
}
答案 0 :(得分:1)
根据切换案例,不建议创建IBusinessMapper<T>
的实例,因为它会在您的抽象(接口)和实现之间引入强大的耦合。
您可以使用多态分派:Business
类可以返回自己的映射器。类似的东西:
public abstract class Business
{
public BusinessType BusinessType { get; set; }
public abstract IBusinessMapper GetMapper():
}
但是,由于您的映射器是通用接口,因此您无法从该方法返回公共类型;即使你的开关盒也做不到。我宁愿研究将您的类型映射到字典中的映射器,还是使用IoC来解析IBusinessMapper<T>
,具体取决于业务对象的类型。
所以你的解决方法会变成:
private IBusinessMapper<T> GetBusinessMapper<T>()
{
// find what class implements IBusinessMapper for the type that's being passed
}
有很多方法可以解决您需要的课程:
Business
班级与IBusinessMapper<>
手动编辑进一步研究这个想法,我发现this question值得一读。我真的不确定接受的答案和开关类型,并且发现我更倾向于Jon Skeet和Marc Gravell的一面,在我看来这不是一件坏事;)无论如何你可能有兴趣阅读它
答案 1 :(得分:0)
是的,你可以在某些情况下必须使用它。这称为Abstract Factory,或其某种形状。或者Factory Method,这可能最适合您的情况。
基本思想是提供一个函数/类,你没有指定一些具体的类型,但你“发出”关于所需类型的信号,而工厂构造了真实对象的实例。