当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 模式:工程化实现及扩展——工厂模式

模式:工程化实现及扩展——工厂模式

2019年07月12日  | 移动技术网IT编程  | 我要评论
相比较传统的工厂模式IFactory/Concrete Factory会反复引用并编译代码 但是作为开发人员,我们更希望的是少修改代码,尽量从配置着手也就是设计模式的根本原则之一:开放封闭原则。如果我要增加新的产品,那么修改就比较大了,对于业务来讲还是可以接受的。但是如果可以做到不修改代码是最好的。 ...

相比较传统的工厂模式ifactory/concrete factory会反复引用并编译代码
但是作为开发人员,我们更希望的是少修改代码,尽量从配置着手也就是设计模式的根本原则之一:开放封闭原则。如果我要增加新的产品,那么修改就比较大了,对于业务来讲还是可以接受的。但是如果可以做到不修改代码是最好的。上一份工作中,我印象最深的一句话就是我上司对我说的"能不改代码就别改,能写进配置里的就写到配置里"。因此我们将要增加的工厂类写到配置里面。如此,新的产品类型和工厂类型即便在系统上线后仍可以通过修改配置文件的方式不断补充。但是,还有一个问题,我们仍然需要为每"类"抽象产品定制特定的工厂接口并实现之,也就是"多头管理"问题。泛型可以用来解决这个问题,我们定义一个泛型工厂即可。代码如下:

/// <summary>
/// 工厂接口定义
/// </summary>
/// <remarks>
/// ttarget: 抽象产品类型
/// tsource: 具体产品类型
/// </remarks>
public interface ifactory
{
    #region config and register type mapping

    /// <summary>
    /// 如果需要同时加载配置文件中定义的映射关系,可以按照srp的原则定义独立的配置类型。
    /// 由该配置类型调用这两个接口为factory加载配置信息
    /// </summary>

    ifactory registertype<ttarget, tsource>();  // 注入产品
    ifactory registertype<ttarget, tsource>(string name);   // 注入产品

    #endregion

    #region factory method

    ttarget create<ttarget>();
    ttarget create<ttarget>(string name);

    #endregion
}

public sealed class typeregistry
{
    /// <summary>
    /// default name in type mappings
    /// </summary>
    readonly string defaultname = guid.newguid().tostring();

    /// <summary>
    /// type        :   ttarget, 抽象产品类型
    /// idictionary<string ,type>
    ///     string  :   name
    ///     type    :   tsource, 具体产品类型
    /// </summary>
    idictionary<type, idictionary<string, type>> registry =
        new dictionary<type, idictionary<string, type>>();

    public void registertype(type targettype, type sourcetype)
    {
        registertype(targettype, sourcetype, defaultname);
    }

    public void registertype(type targettype, type sourcetype, string name)
    {
        if(targettype == null) throw new argumentnullexception("targettype");
        if(sourcetype == null) throw new argumentnullexception("sourcetype");
        if(string.isnullorempty(name)) throw new argumentnullexception("name");

        if (!registry.trygetvalue(targettype, out idictionary<string, type> subdictionary))
        {
            subdictionary = new dictionary<string, type>
            {
                { name, sourcetype }
            };
            registry.add(targettype, subdictionary);
        }
        else
        {
            if (subdictionary.containskey(name))
                throw new exception($"{name}重复");
            subdictionary.add(name, sourcetype);
        }
    }

    public type this[type targettype, string name]
    {
        get
        {
            if (targettype == null) throw new argumentnullexception("targettype");
            if (string.isnullorempty(name)) throw new argumentnullexception("name");
            if (registry.count() == 0)
                return null;

            return 
                (registry.where(x => x.key == targettype)).firstordefault().value
                    .where(x => string.equals(name, x.key)).firstordefault().value;
        }
    }

    public type this[type targettype]
    {
        get { return this[targettype, defaultname]; }
    }
}

public class factory : ifactory
{
    protected typeregistry registry = new typeregistry();

    #region ifactory members

    public ifactory registertype<ttarget, tsource>()
    {
        registry.registertype(typeof(ttarget), typeof(tsource));
        return this;
    }

    public ifactory registertype<ttarget, tsource>(string name)
    {
        registry.registertype(typeof(ttarget), typeof(tsource), name);
        return this;
    }

    public ttarget create<ttarget>()
    {
        return (ttarget)activator.createinstance(registry[typeof(ttarget)]);
    }

    public ttarget create<ttarget>(string name)
    {
        return (ttarget)activator.createinstance(registry[typeof(ttarget), name]);
    }

    #endregion
}

上面的示例表明新的工厂类型不仅可以完成经典工厂方法模式所希望实现的各项要求,也满足抽象工厂的要求,同时他可以作为整个项目一个独立的而且是唯一的工厂入口,供项目中各子系统访问和使用。原因在于它的底层将工厂接口与抽象产品类型的依赖关系变成基于clr"万能工厂"类型activator基于参数type的构造。
工厂管理的是其内的产品。我们的工厂接口ifactory有两个功能,一个是往工厂中注入产品,一个是创建指定产品的实例。借助registertype将配置文件中定义的类型映射方希加载到新的具体工厂类型中,也就是重载函数中的参数(name)。我们通过字典dictionary来管理维护工厂内的产品,将抽象产品也就是接口或是抽象类作为key,要考虑到同一接口可以有多个不同的实现,因此我们再维护一个实现类的字典,使用一个唯一的标识作为key就行,value就是实现类。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网