原型模式(Prototype)
原型模式是创建型模式的一种,其特点在于通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。
原型模式多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。

我们先来看看原型模式的经典实现,我们这里已颜色为例来说下经典实现
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication18 { class Program { static void Main(string[] args) { ColorPrototype color = new Color(); color.Red = 255; ColorPrototype color1 = color.Clone(); color1.Blue = 255; } } public interface ColorPrototype { ColorPrototype Clone(); int Red { get; set; } int Green { get; set; } int Blue { get; set; } } public class Color : ColorPrototype { private int _red; private int _green; private int _blue; public int Red { get { return this._red; } set { this._red = value; } } public int Green { get { return this._green; } set { this._green = value; } } public int Blue { get { return this._blue; } set { this._blue = value; } } public ColorPrototype Clone() { return this.MemberwiseClone() as ColorPrototype; } } }

浙公网安备 33010602011771号