我有 1 个接口(interface):
public interface ISummary
{
int EventId {get; set;}
}
还有许多实现这个接口(interface)的具体类:
public class EmployeeSummary : ISummary
{
public int EventId {get; set;},
public int TotalUniqueCount {get; set;}
public int Location {get; set;}
}
public class CarSummary : ISummary
{
public int EventId {get; set;}
public int TotalMiles {get; set;}
public int TotalHours {get; set;}
}
等....
唯一的共享属性是 EventId
。有没有办法让 1 个工厂方法创建所有这些摘要对象?我想要 1 个入口点来决定要创建哪些对象。
所以像这样:
public ISummary CreateSummary(ConcreteObjectType with properties)
{
if EmployeeSummary
--Call this method to create and return EmployeeSummary
if CarSummary
--Call this method create and return CarSummary
}
我希望其他类中的所有调用都调用此方法,而不是自己创建对象。
我遇到的问题是如何将分配给对象的属性传递给此 CreateSummary
方法,因为对象的所有属性都将不同?
如果有更好的设计模式我应该在这里使用,我愿意改变此时的对象。
最佳答案
嗯,这就是为什么 Factory Method模式存在:
public class SummaryFactory
{
// new instance with values assigned by action delegate or default
public T Create<T>(Action<T> action = null) where T : ISummary, new()
{
var result = new T();
action?.Invoke(result);
return result;
}
// with object to assign value from (map)
public T Create<T>(object map) where T : ISummary, new()
{
var result = new T();
PropertyInfo[] props = map.GetType().GetProperties();
PropertyInfo[] tProps = typeof(T).GetProperties();
foreach (var prop in props)
{
var upperPropName = prop.Name.ToUpper();
var foundProperty = tProps.FirstOrDefault(p => p.Name.ToUpper() == upperPropName);
foundProperty?.SetValue(result, prop.GetValue(map));
}
return result;
}
// new instance without generic parameters
public object Create(Type type)
{
var instance = Activator.CreateInstance(type);
// add some other logic that changes instance
return instance;
}
}
现在你可以使用这个工厂了:
var factory = new SummaryFactory();
var carSummary = factory.Create<CarSummary>();
var carSummary2 = factory.Create<CarSummary>(car => { car.TotalMiles = 50; });
var carSummary3 = factory.Create<CarSummary>(new { TotalMiles = 50 });
var employeeSummary = factory.Create(typeof(EmployeeSummary));
关于c# - 工厂创建相同界面的不同对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39620828/