原型模式





0/5 (0投票)
原型模式基于对象克隆的使用。原型通过克隆其某个具体类来创建新对象。原型模式的
对象是通过克隆其某个具体类。原型模式用于
以下情况
- 您需要向客户端隐藏具体产品类。
- 您希望将类的数量减少到最少。
- 当您使用动态加载时。
- 当您想避免使用复杂的类层次结构
的工厂时。 - 当您的类有少量不同的状态组合时。
原型模式有助于加快对象的实例化,因为
复制对象比构造对象更快。
有关该模式的 UML 图,请访问 dofactory 网站。
C# 示例
让我们来看一个原型用法的例子
#region the Prototype
public abstract class Prototype<T>
{
#region 方法
public T Clone()
{
// create a shallow copy of the object
return (T)this.MemberwiseClone();
}
#endregion
}
#endregion
#region Prototype Concrete
public class ConcretePrototype
Prototype<ConcretePrototype>
{
#region 成员
private string _strName;
#endregion
#region 属性
/// <summary>
/// The name of the prototype
/// </summary>
public string Name
{
get
{
return _strName;
}
}
#endregion
#region 构造函数
/// <summary>
/// Construct a new ConcretePrototype with the
/// given name.
/// </summary>
/// <param name="name">The given name</param>
public ConcretePrototype(string name)
{
_strName = name;
}
#endregion
}
#endregion
在示例中,我创建了一个使用 MemberwiseClone 方法作为克隆实现的 Prototype 类。您应该记住,MemberwiseClone 会创建对象的浅拷贝(复制对象成员)。如果您想要深拷贝,则需要自己实现。ConcretePrototype 只为 Prototype 类添加了属性。
作为克隆实现。您应该记住,MemberwiseClone
会创建对象的浅拷贝(复制对象成员)。如果您想要深
拷贝,则应该自己实现。ConcretePrototype 只添加
属性到 Prototype 类。
构建原型管理器
您可以构建一个管理器来帮助您持有和处理原型具体类,但是
管理器本身不是模式的一部分。这样的管理器的示例可以如下
#region Prototype Manager
/// <summary>
/// The manager isn't part of the design pattern
/// you can use it to manage concretes as a helper
/// class
/// </summary>
public class PrototypeManager
{
#region 成员
private Dictionary<string, ConcretePrototype> concretes =
new Dictionary<string, ConcretePrototype>();
#endregion
#region 属性
/// <summary>
/// Indexer for the concretes which are hold
/// in the PrototypeManager
/// </summary>
public ConcretePrototype this[string name]
{
get
{
return concretes[name];
}
set
{
concretes.Add(name, value);
}
}
#endregion
}
#endregion
摘要
总结来说,原型模式使用克隆方法来使应用程序独立于其产品的创建、组合和表示方式。
应用独立于其产品是如何创建、组合
和表示的。由于 C# 中有 MemberwiseClone 方法,原型模式易于实现。
MemberwiseClone 方法,因此原型模式易于实现。
请注意,原型模式和抽象工厂模式是竞争性的模式。
了解如何实现设计模式有助于理解使用每种模式的权衡,并选择合适的模式。
使用每种模式的权衡,并选择合适的模式。