Singleton Pattern & Prototype Pattern 学习笔记(代码)
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp.DesignPattern.Prototype

{
public class Client
{
public bool Main(string colorName)
{
ColorManager colorManager = ColorManager.Instance ;
if (!colorManager.Contains(colorName))
{
Console.WriteLine("Please add the color!");
return false;
}
ConcreteColorPrototype color = (ConcreteColorPrototype)colorManager[colorName].Clone();
color.Display(colorName);
return true;
}
public void AddColor(string colorName, int red, int green, int blue)
{
ColorManager colorManager = ColorManager.Instance;
colorManager.Add(colorName, new ConcreteColorPrototype(red, green, blue));
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace CSharp.DesignPattern.Prototype

{
public sealed class ColorManager
{
Hashtable colors = new Hashtable();
private static readonly ColorManager instance = new ColorManager();
public static ColorManager Instance
{
get
{
return instance;
}
}
public ColorManager()
{
Console.WriteLine("for test");
}
public ColorPrototype this[string colorName]
{
get
{
return (ColorPrototype)this.colors[colorName];
}
}
public void Add(string colorName,ConcreteColorPrototype value)
{
if (!Contains(colorName))
{
colors.Add(colorName, value);
}
}
public bool Contains(string colorName)
{
return colors.Contains(colorName);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp.DesignPattern.Prototype

{
public class ConcreteColorPrototype:ColorPrototype 
{
private int _red;
private int _blue;
private int _green;
public ConcreteColorPrototype(int red, int green, int blue)
{
this._red = red;
this._green = green;
this._blue = blue;
}
public override ColorPrototype Clone()
{
return (ColorPrototype)this.MemberwiseClone();
}
public void Display(string colorName)
{
Console.WriteLine("{0}'s RGB Values are: {1},{2},{3}",
colorName, _red, _green, _blue);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp.DesignPattern.Prototype

{
public abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
}
以上只是个人练习写的代码。不具有任何的参考性。
浙公网安备 33010602011771号