场景:象棋中每粒子都是红方两颗黑方两颗。比如:車,棋盘中总共有4个,常规做法是有4个对象,通过享元1个对象搞定。
代码如下:

//棋子的外部状态class Protertys { public string name { get; set; } public string position { get; set; } public string color { get; set; } public string capacity { get; set; } public Protertys(string _name,string _position, string _color, string _capacity) { name = _name; position = _position; color = _color; capacity = _capacity; } }//棋子类abstract class Chess { protected string name;//内部对象 public Chess(string _name) { name = _name; } public abstract void Run(Protertys protertys); } class ChineseChess : Chess { public ChineseChess(string _name) : base(_name) { } public override void Run(Protertys protertys) { Console.WriteLine("名字:{0},位置:{1},颜色:{2},性能:{3}", name,protertys.position,protertys.color, protertys.capacity); } } //享元工厂,核心 class ChessFactory { private Hashtable hashTable = new Hashtable(); public Chess GetChess(string key) { if (!hashTable.ContainsKey(key)) { hashTable.Add(key,new ChineseChess(key));//不存在就创建 } return (Chess)hashTable[key]; } public int GetChessCount() { return hashTable.Count; } } //前端 static void Main(string[] args) { Protertys protertys = new Protertys("车","左边第一个","红色","走直线"); Protertys protertys1 = new Protertys("车", "右边第一个", "红色", "走直线"); Protertys protertys2 = new Protertys("车", "左边第一个", "黑色", "走直线"); Protertys protertys3 = new Protertys("车", "右边第一个", "黑色", "走直线"); Protertys protertys4 = new Protertys("马", "左边第二个", "红色", "走日字"); Protertys protertys5 = new Protertys("马", "右边第二个", "红色", "走日字"); Protertys protertys6 = new Protertys("马", "左边第二个", "黑色", "走日字"); Protertys protertys7 = new Protertys("马", "右边第二个", "黑色", "走日字"); ChessFactory chessFactory = new ChessFactory(); Chess Chess1= chessFactory.GetChess(protertys.name); Chess Chess2 = chessFactory.GetChess(protertys1.name); Chess Chess3 = chessFactory.GetChess(protertys2.name); Chess Chess4 = chessFactory.GetChess(protertys3.name); Chess Chess5 = chessFactory.GetChess(protertys4.name); Chess Chess6 = chessFactory.GetChess(protertys5.name); Chess Chess7 = chessFactory.GetChess(protertys6.name); Chess Chess8 = chessFactory.GetChess(protertys7.name); Chess1.Run(protertys); Chess2.Run(protertys1); Chess3.Run(protertys2); Chess4.Run(protertys3); Chess5.Run(protertys4); Chess6.Run(protertys5); Chess7.Run(protertys6); Chess8.Run(protertys7); int count = chessFactory.GetChessCount(); Console.WriteLine("总共有{0}个对象",count); Console.ReadLine(); }

总结:棋盘上的車马总共是8个对象,然后最终只生成了2个对象,大大节约了内存。
享元模式就是运用共享技术,有效的支持大量细粒度对象(字面意思很贴切:共享元数据)。
方式:把对象的特性抽离出来当外部状态然后传入对象。
优点:避免大量的相似的类开销,可减少对象的实例数量。
缺点:程序复杂化。

和简单工厂类似,和单例模式类似。
单例只有一个实例,而享元可以有多个实例。