GoF Factory设计模式的命名规范是什么?

4
这种模式使用抽象工厂,然后是工厂的实现。
我确信这两个类有一个标准的命名规范,但我不知道它是什么。
例如: public abstract class ChocolateFactory { }; public class MyChocolateFactory { } : ChocolateFactory
这里的标准约定是什么?
我在考虑是ChocolateFactoryBase还是ConcreteChocolateFactory,但也许还有其他的(就像枚举通常会加上Enum后缀一样,例如PetTypeEnum,这样你就可以做PetTypeEnum PetType;)
希望这不是主观的。

两个名称都没有任何意义,所以它们都同样糟糕。通常最好使用描述性的名称,例如“WhiteChocolateFactory”,它是一个具体的工厂。仅仅为了创建工厂而创建工厂是没有意义的;通常只有在存在不同的实现来创建某个特定“类”的东西时才会这样做。使用该类的名称作为前缀是有意义的。 - atlaste
根据GoF(而不是简单工厂)的说法,你应该创建一个抽象版本和一个实现版本,而不仅仅是创建一个简单的工厂,例如CustomerFactory,这样将来有人可以用自己的实现替换工厂。 - NibblyPig
是的,我知道这个模式;(从我的记忆中... :))他们解释的上下文是,例如,如果您有一个“小部件”集合,您可以交换渲染引擎。如果您查看示例,您将看到它们使用渲染引擎的名称作为工厂名称。至于我的评论:请注意,渲染引擎很可能随着时间的推移而改变(因为每天都会发明新的UI工具包),因此在这里使用工厂是有意义的;如果不改变,使用工厂就没有意义。 - atlaste
我猜 DefaultChocolateFactory() 会是最合理的选择。 - NibblyPig
如果你有一个抽象工厂,你应该总是提供一个默认实现,但由于问题是关于命名的:默认...太糟糕了!默认工厂会做什么?为什么它是默认的?所有其他实现都是特殊的吗? - MrWombat
3个回答

6

问题和答案

好的,这个问题始于抽象工厂的命名问题。通常情况下,使用“正式”名称来表示你正在做什么(例如,Factory、Decorator等),并加上具体实现的描述(例如,Snickers、Mars、MotifWidget等)。

因此,你创建一个MSSQLConnection,这是你要描述的具体内容,以及一个Factory,这意味着它遵循工厂模式的特性。

好的,到目前为止我们已经讨论了命名和原始问题。现在是时候谈谈有趣的东西了。讨论转向如何在C#中实现抽象工厂,这是另一个话题。我在实现所有设计模式的C#方面做了相当多的工作,在这里我将分享一些关于工厂的细节。以下是:

抽象工厂和工厂

抽象工厂基本上是一个基类或接口和一个具体实现的组合。如果你共享大量代码,则需要一个基类;如果不需要,则需要一个接口。

我通常区分“工厂”和“抽象工厂”。一个工厂是用于创建某种类型对象的东西,而“抽象工厂”是用于创建任意类型对象的东西。因此,实现一个抽象工厂就是一个工厂。这对下一部分信息很重要。

工厂模式

支持RTTI的语言能够实现工厂模式。工厂模式是用于创建对象的东西。最简单的实现是一个只包含创建对象方法的类,例如:

// ...

public void CreateConnection()
{
    return new SqlConnection();
}

// ...

你通常使用它来抽象事物。例如,在HTML解析器中生成XML节点的东西,会根据HTML标签创建某种类型的节点。
工厂通常根据运行时信息做出决策。因此,可以将工厂模式泛化,实现类似以下内容:
public T Create(string name) 
{
    // lookup constructor, invoke.
}

使用RTTI很容易创建一个通用的工厂模式,为每个名称存储一个Type即可。查找名称,使用反射创建对象。完成。
而且,相较于手动制作所有工厂,你需要编写更少的代码。因为所有实现都是相同的,你可以将其放在基类中,并在静态构造函数中填充字典。
抽象工厂基本上是创建对象的工厂集合,与工厂模式相同。唯一共享的是接口(例如Create),或者可以使用继承来创建抽象。
实现非常简单,我就不多说了。
让我们回到GoF的例子。他们谈论了MotifFactory和PMFactory。在未来,我们还会遇到其他UI组件,我们需要ASPNETFactory或SilverlightFactory。然而,未来是未知的,如果没有必要,我们宁愿不要发布旧的DLL——毕竟这不够灵活。
如果我们想向工厂添加新方法,那么第二个问题就出现了。这意味着这样做将涉及更改所有工厂。正如您所料,我不想在多个地方更改此内容。
幸运的是,我们可以解决这两个问题。接口是相同的(甚至可以泛化),因此我们可以在运行时简单地向工厂添加新功能。
我们可以使用属性告诉类应该由某个工厂实例化,而不是告诉工厂要创建什么对象。我们还可以在装载程序集时扫描所有类型,因此如果加载了一个程序集,我们可以动态地构建新的工厂。
为此我牺牲了编译时检查,但由于工厂模式通常使用运行时信息,这并不一定是问题。
总之,这是我的工厂代码:
/// <summary>
/// This attribute is used to tag classes, enabling them to be constructed by a Factory class. See the <see cref="Factory{Key,Intf}"/> 
/// class for details.
/// </summary>
/// <remarks>
/// <para>
/// It is okay to mark classes with multiple FactoryClass attributes, even when using different keys or different factories.
/// </para>
/// </remarks>
/// <seealso cref="Factory{Key,Intf}"/>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class FactoryClassAttribute : Attribute
{
    /// <summary>
    /// This marks a class as eligible for construction by the specified factory type.
    /// </summary>
    /// <example>
    /// [FactoryClass("ScrollBar", typeof(MotifFactory))]
    /// public class MotifScrollBar : IControl { }
    /// </example>
    /// <param name="key">The key used to construct the object</param>
    /// <param name="factoryType">The type of the factory class</param>
    public FactoryClassAttribute(object key, Type factoryType)
    {
        if ((factoryType.IsGenericType &&
             factoryType.GetGenericTypeDefinition() == typeof(Factory<,>)) ||
            factoryType.IsAbstract || 
            factoryType.IsInterface)
        {
            throw new NotSupportedException("Incorrect factory type: you cannot use GenericFactory or an abstract type as factory.");
        }
        this.Key = key;
        this.FactoryType = factoryType;
    }

    /// <summary>
    /// The key used to construct the object when calling the <see cref="Factory{Key,Intf}.Create(Key)"/> method.
    /// </summary>
    public object Key { get; private set; }

    /// <summary>
    /// The type of the factory class
    /// </summary>
    public Type FactoryType { get; private set; }
}

/// <summary>
/// Provides an interface for creating related or dependent objects.
/// </summary>
/// <remarks>
/// <para>
/// This class is an implementation of the Factory pattern. Your factory class should inherit this Factory class and 
/// you should use the [<see cref="FactoryClassAttribute"/>] attribute on the objects that are created by the factory.
/// The implementation assumes all created objects share the same constructor signature (which is not checked by the Factory). 
/// All implementations also share the same <typeparamref name="Intf"/> type and are stored by key. During runtime, you can 
/// use the Factory class implementation to build objects of the correct type.
/// </para>
/// <para>
/// The Abstract Factory pattern can be implemented by adding a base Factory class with multiple factory classes that inherit from 
/// the base class and are used for registration. (See below for a complete code example).
/// </para>
/// <para>
/// Implementation of the Strategy pattern can be done by using the Factory pattern and making the <typeparamref name="Intf"/>
/// implementations algorithms. When using the Strategy pattern, you still need to have some logic that picks when to use which key.
/// In some cases it can be useful to use the Factory overload with the type conversion to map keys on other keys. When implementing 
/// the strategy pattern, it is possible to use this overload to determine which algorithm to use.
/// </para>
/// </remarks>
/// <typeparam name="Key">The type of the key to use for looking up the correct object type</typeparam>
/// <typeparam name="Intf">The base interface that all classes created by the Factory share</typeparam>
/// <remarks>
/// The factory class automatically hooks to all loaded assemblies by the current AppDomain. All classes tagged with the FactoryClass
/// are automatically registered.
/// </remarks>
/// <example>
/// <code lang="c#">
/// // Create the scrollbar and register it to the factory of the Motif system
/// [FactoryClass("ScrollBar", typeof(MotifFactory))]
/// public class MotifScrollBar : IControl { }
/// 
/// // [...] add other classes tagged with the FactoryClass attribute here...
///
/// public abstract class WidgetFactory : Factory&lt;string, IControl&gt;
/// {
///     public IControl CreateScrollBar() { return Create("ScrollBar") as IScrollBar; }
/// }
///
/// public class MotifFactory : WidgetFactory { }
/// public class PMFactory : WidgetFactory { }
///
/// // [...] use the factory to create a scrollbar
/// 
/// WidgetFactory widgetFactory = new MotifFactory();
/// var scrollbar = widgetFactory.CreateScrollBar(); // this is a MotifScrollbar intance
/// </code>
/// </example>
public abstract class Factory<Key, Intf> : IFactory<Key, Intf>
    where Intf : class
{
    /// <summary>
    /// Creates a factory by mapping the keys of the create method to the keys in the FactoryClass attributes.
    /// </summary>
    protected Factory() : this((a) => (a)) { }

    /// <summary>
    /// Creates a factory by using a custom mapping function that defines the mapping of keys from the Create 
    /// method, to the keys in the FactoryClass attributes.
    /// </summary>
    /// <param name="typeConversion">A function that maps keys passed to <see cref="Create(Key)"/> to keys used with [<see cref="FactoryClassAttribute"/>]</param>
    protected Factory(Func<Key, object> typeConversion)
    {
        this.typeConversion = typeConversion;
    }

    private Func<Key, object> typeConversion;
    private static object lockObject = new object();
    private static Dictionary<Type, Dictionary<object, Type>> dict = null;

    /// <summary>
    /// Creates an instance a class registered with the <see cref="FactoryClassAttribute"/> attribute by looking up the key.
    /// </summary>
    /// <param name="key">The key used to lookup the attribute. The key is first converted using the typeConversion function passed 
    /// to the constructor if this was defined.</param>
    /// <returns>An instance of the factory class</returns>
    public virtual Intf Create(Key key)
    {
        Dictionary<Type, Dictionary<object, Type>> dict = Init();
        Dictionary<object, Type> factoryDict;
        if (dict.TryGetValue(this.GetType(), out factoryDict))
        {
            Type t;
            return (factoryDict.TryGetValue(typeConversion(key), out t)) ? (Intf)Activator.CreateInstance(t) : null;
        }
        return null;
    }

    /// <summary>
    /// Creates an instance a class registered with the <see cref="FactoryClassAttribute"/> attribute by looking up the key.
    /// </summary>
    /// <param name="key">The key used to lookup the attribute. The key is first converted using the typeConversion function passed 
    /// to the constructor if this was defined.</param>
    /// <param name="constructorParameters">Additional parameters that have to be passed to the constructor</param>
    /// <returns>An instance of the factory class</returns>
    public virtual Intf Create(Key key, params object[] constructorParameters)
    {
        Dictionary<Type, Dictionary<object, Type>> dict = Init();
        Dictionary<object, Type> factoryDict;
        if (dict.TryGetValue(this.GetType(), out factoryDict))
        {
            Type t;
            return (factoryDict.TryGetValue(typeConversion(key), out t)) ? (Intf)Activator.CreateInstance(t, constructorParameters) : null;
        }
        return null;
    }

    /// <summary>
    /// Enumerates all registered attribute keys. No transformation is done here.
    /// </summary>
    /// <returns>All keys currently known to this factory</returns>
    public virtual IEnumerable<Key> EnumerateKeys()
    {
        Dictionary<Type, Dictionary<object, Type>> dict = Init();
        Dictionary<object, Type> factoryDict;
        if (dict.TryGetValue(this.GetType(), out factoryDict))
        {
            foreach (object key in factoryDict.Keys)
            {
                yield return (Key)key;
            }
        }
    }

    private void TryHook()
    {
        AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(NewAssemblyLoaded);
    }

    private Dictionary<Type, Dictionary<object, Type>> Init()
    {
        Dictionary<Type, Dictionary<object, Type>> d = dict;
        if (d == null)
        {
            lock (lockObject)
            {
                if (dict == null)
                {
                    try
                    {
                        TryHook();
                    }
                    catch (Exception) { } // Not available in this security mode. You're probably using shared hosting

                    ScanTypes();
                }
                d = dict;
            }
        }
        return d;
    }

    private void ScanTypes()
    {
        Dictionary<Type, Dictionary<object, Type>> classDict = new Dictionary<Type, Dictionary<object, Type>>();
        foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
        {
            AddAssemblyTypes(classDict, ass);
        }
        dict = classDict;
    }

    private void AddAssemblyTypes(Dictionary<Type, Dictionary<object, Type>> classDict, Assembly ass)
    {
        try
        {
            foreach (Type t in ass.GetTypes())
            {
                if (t.IsClass && !t.IsAbstract &&
                    typeof(Intf).IsAssignableFrom(t))
                {
                    object[] fca = t.GetCustomAttributes(typeof(FactoryClassAttribute), false);
                    foreach (FactoryClassAttribute f in fca)
                    {
                        if (!(f.Key is Key))
                        {
                            throw new InvalidCastException(string.Format("Cannot cast key of factory object {0} to {1}", t.FullName, typeof(Key).FullName));
                        }
                        Dictionary<object, Type> keyDict;
                        if (!classDict.TryGetValue(f.FactoryType, out keyDict))
                        {
                            keyDict = new Dictionary<object, Type>();
                            classDict.Add(f.FactoryType, keyDict);
                        }
                        keyDict.Add(f.Key, t);
                    }
                }
            }
        }
        catch (ReflectionTypeLoadException) { } // An assembly we cannot process. That also means we cannot use it.
    }

    private void NewAssemblyLoaded(object sender, AssemblyLoadEventArgs args)
    {
        lock (lockObject)
        {
            // Make sure new 'create' invokes wait till we're done updating the factory
            Dictionary<Type, Dictionary<object, Type>> classDict = new Dictionary<Type, Dictionary<object, Type>>(dict);
            dict = null;
            Thread.MemoryBarrier();

            AddAssemblyTypes(classDict, args.LoadedAssembly);
            dict = classDict;
        }
    }
}

1

我不知道这里是否有任何惯例,但我认为这高度取决于情况。我仅在依赖注入场景中使用AbstractFactory,在那里我想在运行时创建类型并且必须提供抽象。

  1. "abstract"部分可以是一个接口 -> 惯例应该是 I名称
  2. 您的基类应描述其实现中的“共同”事物,信息位于上下文中:如果在您的上下文中,ChocolateFactory可能是一个“抽象”概念,则实现(应描述具体的事物(MyChocolateFactory不是一个好名称))应显示它们的(is)关系,但也应显示具体用例。
  3. 关于您的评论:如果没有其他工厂实现的需要,不要使用抽象工厂,只为可能的将来用例 ;)

1
你可以使用类似于这样的代码:

您可以像这样使用:

// general interface for abstract factory (this is optional)
public abstract class AbstractFactory { };

// interface that uses a type of factory and produce abstract product
public abstract class AbstractChocolateFactory : AbstractFactory  { };

// family of concrete factories that produce concrete products
public class NestleChocolateFactory { } : AbstractChocolateFactory 

public class SwissChocolateFactory { } : AbstractChocolateFactory 

这只是一个想法,但使用抽象工厂模式的实现完全取决于您具体的任务。

抽象工厂基类的原因是什么?有哪些成员可以在其中,以及您能获得什么好处? - MrWombat
1
但是如果有55个方法,你将会得到一个(可怕的)类接口和一个可怕的类设计;) - MrWombat
1
有时候并不是你设计了你所知道的所有东西 :) 也许这个接口是由其他人设计的,而你只需要与它一起工作。我只是想指出接口很好,但有时使用抽象类也很酷。在我看来,这完全取决于问题本身。 - Fabjan
1
根据GoF工厂模式,您需要创建一个抽象的SnickersFactory(),然后实现它,这样如果将来有人想以不同的方式创建Snickers,他们可以在不改变代码的情况下这样做(开闭原则)。如果是SQLConnectionFactory(),并且他们想以不同的方式实现它,那么这种方法就更有意义了。 - NibblyPig
1
@Fabjan 这就是为什么抽象类很差,如果你声明了抽象方法但从未实现它们,那就是糟糕的设计。使用接口可以告诉开发人员这是你的契约,请使用它或离开。 - Thorarins
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接