艾伟_转载:一个简单的 Generic Factory 类

简介:   简单的工厂类的一个使用场景是, 假设有一个基类 BaseClass, 和一系列的子类 A, B, C, 工厂类根据某个参数,例如字符串 “A”, “B”, “C” 创建出相应的子类。 举例如下:public class Factory{ public static BaseClass...

  简单的工厂类的一个使用场景是, 假设有一个基类 BaseClass, 和一系列的子类 A, B, C, 工厂类根据某个参数,例如字符串 “A”, “B”, “C” 创建出相应的子类。 举例如下:

public class Factory
{
    public static BaseClass Create(string name)
    {
        switch (name)
        {
            case "A": return new A();
            case "B": return new B();
            case "C": return new C();
            default: throw new ArgumentException("Wrong Name");
        }
    }
}

  这里的一个问题是, 当子类增加或减少时, Factory 类 需要相应的改动。 有没有办法可以只是改动子类本身, 而不用修改Factory类呢, 当然有,这里我举一个简单的实现。

  基本思想是在每个子类上附加一个 Attribute, 定义如下:

[AttributeUsage(AttributeTargets.Class)]
public class FactoryKeyAttribute : Attribute
{
    public object Key { get; set; }
}

  假设我们有基类和子类实现如下

public abstract class BaseClass {}
[FactoryKey(Key = "Standard")]
public class Standard : BaseClass {}
[FactoryKey(Key = "Enterprise")]
public class Enterprise : BaseClass {}
[FactoryKey(Key = "Lite")]
public class Lite : BaseClass {}

 

  假设这些类都在同一个 Assembly中 (对于不在同一个Assembly的,实现会稍微复杂些)工厂类需要预先加载 Key => Type 的Mapping, 然后根据Key创建不同的实例, 实现如下:

public static class Factory<TKey, TBaseClass>
{
    private static readonly IDictionary<TKey, Type> TypeDict = Init();
    private static IDictionary<TKey, Type> Init()
    {
        var dict = from type in Assembly.GetExecutingAssembly().GetTypes()
                   let key = (FactoryKeyAttribute)Attribute.GetCustomAttribute(type, typeof(FactoryK
eyAttribute
)) where key != null && type.IsSubclassOf(typeof(TBaseClass)) select new { Key = key, Value = type }; return dict.ToDictionary(kvp => (TKey)kvp.Key.Key, kvp => kvp.Value); } public static TBaseClass CreateInstance(TKey key) { Type type; if (TypeDict.TryGetValue(key, out type)) { return (TBaseClass)Activator.CreateInstance(type); } throw new ArgumentException("Incorrect Key!"); } }

  使用方法也很简单:

BaseClass s = Factory<string, BaseClass>.CreateInstance("Standard");
BaseClass l = Factory<string, BaseClass>.CreateInstance("Lite");
BaseClass e = Factory<string, BaseClass>.CreateInstance("Enterprise");

 

  对于其他类型的Key,比如 Enum, 或其他类型的基类, 改变Factory 的类型参数即可。

目录
打赏
0
0
0
0
52
分享
相关文章
Consider defining a bean of type ‘com.bsj.system.service.RedisService‘ in your configuration
Consider defining a bean of type ‘com.bsj.system.service.RedisService‘ in your configuration
589 0
php设计模式-简单工厂模式 (Simple Factory)
简单工厂模式又称为静态工厂方法模型,它属于类创建型模式,简单工厂并不属于23种设计模式,刚开始学习设计模式的同学,对简单工厂模式、工厂方法、抽象工厂中的工厂一知半解,其实白话点来说:这些模式一定会有一个工厂类,子类并不需要知道工厂细节,只需新建工厂创建产品即好。
144 0
SpringMVC - Failed to instantiate Specified class is an interface
SpringMVC - Failed to instantiate Specified class is an interface
613 0
Entity Framework Core(3)-配置DbContext
设计时 DbContext 配置 EF Core 设计时工具如迁移需要能够发现和创建的工作实例DbContext以收集有关应用程序的实体类型以及它们如何映射到数据库架构的详细信息的类型。 此过程可以为自动,只要该工具可以轻松地创建DbContext,会将其配置同样到它如何将配置在运行时的方式。
992 0
使用C# (.NET Core) 实现简单工厂(Simple Factory) 和工厂方法设计模式 (Factory Method Pattern)
本文源自深入浅出设计模式. 只不过我是使用C#/.NET Core实现的例子.   前言 当你看见new这个关键字的时候, 就应该想到它是具体的实现. 这就是一个具体的类, 为了更灵活, 我们应该使用的是接口(interface).
1473 0
使用ControllerAdvice注意事项,Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]
前言 ControllerAdvice非常好用,可以把系统内部的异常统一处理。用起来也很简单。比如,http://www.cnblogs.com/woshimrf/p/spring-web-400.html 而Spring提供了一个base类ResponseEntityExceptionHandler,可以使用这个来处理。
2747 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等