Skip to main content
 首页 » 编程设计

c#之由枚举属性驱动的工厂

2024年02月06日13虾米哥

我有这样一种情况,工厂模式似乎很合适:

 enum Food {       
  Cake,       
  Cookies,       
  Milk, 
  CannedBeans 
} 
 
public static class FoodMetaDataFactory{     
    public static IFood GetMetaData(Food foodType){  //takes a food enum value as a parameter 
       switch(foodType){ 
          case Food.Milk: 
             return new MilkMetaData(); 
          case Food.CannedBeans: 
             return new CannedBeansMetaData(); 
          case Food.Cookies: 
             return new CookiesMetaData(); 
          case Food.Cake: 
             return new CakeMetaData(); 
       } 
    }     
} 

但是,我宁愿有像这样更具声明性的模式:

enum Food { 
  [FoodMetaDataAttribute(typeof(CakeMetaData))]     
  Cake, 
  [FoodMetaDataAttribute(typeof(CookiesMetaData))]    
  Cookies, 
  [FoodMetaDataAttribute(typeof(MilkMetaData))]    
  Milk, 
  [FoodMetaDataAttribute(typeof(CannedBeansMetaData))]    
  CannedBeans 
} 
 
public static class FoodMetaDataFactory{     
    public static IFood GetMetaData(Food foodType){  //takes a food enum value as a parameter 
        //reflectively retrieve FoodMetaDataAttribute 
        Type enumType = typeof(Food); 
        var memInfo = enumType.GetMember(foodType.ToString()); 
        //assume one item returned 
        var foodMetaDataAttributes = memInfo[0].GetCustomAttributes(typeof(FoodMetaDataAttribute), 
false); 
        // now access the property telling us the concrete type of the metadata class(this is the type passed in the attribute's declaration 
        Type targetType = ((FoodMetaDataAttribute)foodMetaDataAttributes[0]).MetaDataProviderType;      
 
        //not done yet, now we need to reflectively instantiate targetType, something like this             
        ConstructorInfo ctor = targetType.GetConstructor(new[] { }); 
        //invoke the constructor, returning concrete instance such as CakeMetaData 
        return ctor.Invoke(new object[] {}) as IFood;      
    }     
} 
 
[AttributeUsage(AttributeTargets.Field)] 
public class FoodMetaDataAttribute : Attribute 
{       
   public FoodMetaDataAttribute(Type metaDataProviderType){ 
      MetaDataProviderType = metaDataProviderType; 
   } 
   public Type MetaDataProviderType { get; set; } 
} 

我喜欢这个,因为任何向枚举添加新值的人都清楚他们需要一个元数据类并在属性中声明它。这个 IMO 比必须记住在工厂中修改开关盒要好。

起初看起来很简单,直到我开始考虑 GetMetaData 的实现,它必须反射性地检索属性、typeof 参数,然后反射性地实例化 MetaData 类。 我在创建属性类方面没有经验,所以这个问题的主要驱动力是希望也许有一种更简单的方法来使用属性来实现这一点。如果属性类没有那么多限制,例如在使用泛型类型时,我会以我喜欢的方式完成此操作并确保编译时安全。

此提议的解决方案没有编译时安全性。您可以将类型传递给不实现 IFood 的属性,这是 MilkMetaData 等元数据类的最低要求。如果属性允许泛型类型参数,我会使用它而不是 typeof 并且可以应用 where T:IFood

有没有更好的方法利用属性来完成从枚举值到具体类的映射?

请您参考如下方法:

在这些情况下我通常做的是创建一个工厂字典,例如:

private IDictionary<MyEnum, Func<IMyInterface>> Factories = new Dictionary<MyEnum, Func<IMyInterface>> { 
    { MyEnum.MyValue, () => new MyType() }, 
    // etc. 
} 

简单且易于维护、扩展或验证。您可以通过以下方式创建实例:

IMyInterface instance; 
if(!Factories.TryGetValue(enumValue, out instance)) 
    throw new Exception(string.Format("No factory for enum value {0}", enumValue)); 
return instance; 

请注意,将枚举与实际实例分开应该是一件好的事情(将实现与数据分开)。否则,我建议您简单地将实际类型传递给泛型方法。