標籤:
using System;namespace ConsoleApplication5{ class Program { static void Main(string[] args) { // 孫悟空 原型 MonkeyKingPrototype prototypeMonkeyKing = new ConcretePrototype("MonkeyKing"); // 變一個 MonkeyKingPrototype cloneMonkeyKing = prototypeMonkeyKing.Clone() as ConcretePrototype; Console.WriteLine("Cloned1:\t" + cloneMonkeyKing.Id); // 變兩個 MonkeyKingPrototype cloneMonkeyKing2 = prototypeMonkeyKing.Clone() as ConcretePrototype; Console.WriteLine("Cloned2:\t" + cloneMonkeyKing2.Id); Console.ReadLine(); } } /// <summary> /// 孫悟空原型 /// </summary> public abstract class MonkeyKingPrototype { public string Id { get; set; } public MonkeyKingPrototype(string id) { this.Id = id; } // 複製方法,即孫大聖說“變” public abstract MonkeyKingPrototype Clone(); } /// <summary> /// 建立具體原型 /// </summary> public class ConcretePrototype : MonkeyKingPrototype { public ConcretePrototype(string id) : base(id) { } /// <summary> /// 淺拷貝 /// </summary> /// <returns></returns> public override MonkeyKingPrototype Clone() { // 調用MemberwiseClone方法實現的是淺拷貝,另外還有深拷貝 return (MonkeyKingPrototype)this.MemberwiseClone(); } }}
6.原型模式(Prototype Pattern)