using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignPattern
{
//享元模式
//运用共享技术有效的支持大量细粒度对象的复用。
internal class FlyweightPattern
{
public void main()
{
IgoChessman black1, black2, black3, white1, white2;
IgoChessmanFactory factory;
//获取享元工厂对象
factory = IgoChessmanFactory.GetInstance();
black1 = factory.GetIgoChessman("b");
black2 = factory.GetIgoChessman("b");
black3 = factory.GetIgoChessman("b");
Console.WriteLine("判断两颗黑子是否相同:" + (black1 == black2));
//通过享元工厂获取两颗白子
white1 = factory.GetIgoChessman("w");
white2 = factory.GetIgoChessman("w");
Console.WriteLine("判断两颗白子是否相同:" + (white1 == white2));
black1.Display(new Coordinates(1,2));
black2.Display(new Coordinates(3, 4));
black3.Display(new Coordinates(1, 3));
white1.Display(new Coordinates(2, 5));
white2.Display(new Coordinates(2, 4));
//输出结果
//判断两颗
//判断两颗黑子是否相同:TRUE
//判断两颗白子是否相同:TRUE
//黑色,棋子位置:1,2
//黑色,棋子位置:3,4
//黑色,棋子位置:1,3
//白色,棋子位置:2,5
//白色,棋子位置:2,4
}
}
class Coordinates
{
private int x;
private int y;
public int X
{
get { return x; }
set { x = value; }
}
public int Y
{
set { y = value; }
get { return y; }
}
public Coordinates(int x, int y)
{
this.X = x;
this.Y = y;
}
}
abstract class IgoChessman
{
public abstract string GetColor();
public void Display(Coordinates coord)
{
Console.WriteLine("棋子颜色:{0},棋子位置:{1},{2}", this.GetColor(), coord.X, coord.Y);
}
}
class BlackIgoChessman : IgoChessman
{
public override string GetColor()
{
return "黑色";
}
}
class WhiteIgoChessman : IgoChessman
{
public override string GetColor()
{
return "白色";
}
}
class IgoChessmanFactory
{
private static IgoChessmanFactory instance = new IgoChessmanFactory();
private Hashtable ht;
private IgoChessmanFactory()
{
ht = new Hashtable();
IgoChessman black, white;
black = new BlackIgoChessman();
white = new WhiteIgoChessman();
ht.Add("b", black);
ht.Add("w", white);
}
//返回享元工厂类的唯一实例
public static IgoChessmanFactory GetInstance()
{
return instance;
}
//通过KEY获取存储再Hashtable里的享元对象
public IgoChessman GetIgoChessman(string color)
{
return (IgoChessman)ht[color];
}
}
}
《C#设计模式》==>享元模式
最新推荐文章于 2024-11-08 14:47:03 发布