設計模式-享元模式
阿新 • • 發佈:2018-05-29
設計模式 享元模式 場景:象棋中每粒子都是紅方兩顆黑方兩顆。比如:車,棋盤中總共有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個對象,大大節約了內存。
享元模式就是運用共享技術,有效的支持大量細粒度對象(字面意思很貼切:共享元數據)。
方式:把對象的特性抽離出來當外部狀態然後傳入對象。
優點:避免大量的相似的類開銷,可減少對象的實例數量。
缺點:程序復雜化。
和簡單工廠類似,和單例模式類似。
單例只有一個實例,而享元可以有多個實例。
設計模式-享元模式