如果您希望开发人员所要做的只是创建类,并且您的经理将能够自动创建它的实例,请使用 Reflection 收集提供给用户的选项列表,并使用 Activator 创建实例请求。
Dictionary<string, Type> DerivedOfferings{get;set;}
... //somewhere in the setup of your manager.
foreach (Type t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IEmtRequestProcessor)))))
{
DerivedOfferings.Add(t.Name, t);
}
//provide list of options to users.
IList<string> GetOfferingOptions(){
return DerivedOfferings.Keys.ToList();
}
...
public BaseClass GetOffering(string name){
return (BaseClass)Activator.CreateInstance(DerivedOfferings[type]);
}
如果需要执行一些逻辑来决定创建哪个派生产品,您可以为开发人员提供一个属性来装饰他们的类,使用该属性来保存执行逻辑所针对的信息。
public sealed class CreatureAttribute:Attribute
{
public int NumberOfLegs{get;set;}
public Color HairColor{get;set;}
public int NumberOfWings{get;set;}
public bool BreathsFire{get;set;}
}
[CreatureAttribute(NumberOfLegs=6, HairColor = Color.Magenta, NumberOfWings=0, BreathsFire=True)]
public class PurpleDragon: ICreature
{
...
}
然后在枚举期间检索这些并将它们与选项一起存储。
List<CreatureCriteria> CreatureOptions{get;set;}
EnumerateOptions()
{
foreach (Type t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ICreature)))))
{
foreach (CreatureAttribute creatureAttribute in
t.GetCustomAttributes(typeof (CreatureAttribute), false)
.Cast<CreatureAttribute>()
{
CreatureOptions.Add(
new CreatureCriteria{
Legs = creatureAttribute.NumberOfLegs,
HairColor = creatureAttribute.HairColor,
...
ConcreteType = t
}
);
}
}
}
并根据用户提供的标准进行评估..
ICreature CreateCreature(CreatureCriteria criteria){
CreatureCriteria bestMatch = CreatureOptions.FindBestMatch(criteria);
// perform logic comparing provided criteria against CreatureOptions to find best match.
return (ICreature)Activator.CreateInstance(bestMatch.ConcreteType);
}