客户角色:客户端类向原型管理器提出创建对象的请求。
抽象原型角色:通常由一个c#接口或抽象类实现,此角色给出所有的具体原型类所需的接口,在c#中,抽象原型角色通常实现了ICloneable接口。
具体原型角色:被复制的对象,此角色需要实现抽象的原型角色所要求的接口。
原型管理器角色:创建具体原型类的对象,并记录每一个被创建的对象。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace Simple_Factory
{
/// <summary>
/// 抽象原型类
/// </summary>
abstract class ColorProtoType
{
public abstract ColorProtoType Clone();
}
{
/// <summary>
/// 抽象原型类
/// </summary>
abstract class ColorProtoType
{
public abstract ColorProtoType Clone();
}
/// <summary>
/// 具体原型类
/// </summary>
class Color : ColorProtoType
{
private int red, green, blue;
/// 具体原型类
/// </summary>
class Color : ColorProtoType
{
private int red, green, blue;
public Color(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}
{
this.red = red;
this.green = green;
this.blue = blue;
}
public override ColorProtoType Clone()
{
return (ColorProtoType)this.MemberwiseClone();
}
{
return (ColorProtoType)this.MemberwiseClone();
}
public void Display()
{
Console.WriteLine("RGB values are:{0},{1},{2}", red, green, blue);
}
}
{
Console.WriteLine("RGB values are:{0},{1},{2}", red, green, blue);
}
}
/// <summary>
/// 原型管理器
/// </summary>
class ColorManager
{
Hashtable colors = new Hashtable();
/// 原型管理器
/// </summary>
class ColorManager
{
Hashtable colors = new Hashtable();
public ColorProtoType this[string name]
{
get
{
return (ColorProtoType)colors[name];
}
}
}
{
get
{
return (ColorProtoType)colors[name];
}
}
}
/// <summary>
/// 客户端
/// </summary>
class PrototypeApp
{
public static void Main(string[] args)
{
ColorManager colorManager = new ColorManager();
/// 客户端
/// </summary>
class PrototypeApp
{
public static void Main(string[] args)
{
ColorManager colorManager = new ColorManager();
colorManager["red"] = new Color(255, 0, 0);
colorManager["green"] = new Color(0, 255, 0);
colorManager["blue"] = new Color(0, 0, 255);
colorManager["green"] = new Color(0, 255, 0);
colorManager["blue"] = new Color(0, 0, 255);
string colorName = "red";
Color c1 = (Color)colorManager[colorName].Clone();
c1.Display();
Color c1 = (Color)colorManager[colorName].Clone();
c1.Display();
colorName = "peace";
Color c2 = (Color)colorManager[colorName].Clone();
c2.Display();
Color c2 = (Color)colorManager[colorName].Clone();
c2.Display();
colorName = "flame";
Color c3 = (Color)colorManager[colorName].Clone();
c3.Display();
}
}
}
Color c3 = (Color)colorManager[colorName].Clone();
c3.Display();
}
}
}
使用MemberwiseClone()进行浅拷贝,使用Clone()进行深拷贝。