享元模式
作者:互联网
具体就是在工厂中保存对象的引用,通过共享对象来减少内存的开销.对象之间的差异使用外部对象来处理.
class Program { /// <summary> /// 享元模式例子 /// </summary> /// <param name="args"></param> static void Main(string[] args) { FlyWeightFactory factory = new FlyWeightFactory(); var whiteChessman = factory.GetChessman("白"); var blockCheeman = factory.GetChessman("黑"); whiteChessman.Use(new ChessmanPostion() { X = 1, Y = 4 }); blockCheeman.Use(new ChessmanPostion() { X = 1, Y = 2 }); Console.Read(); } } /// <summary> /// 享元工厂(这里可将工厂设置为静态) /// </summary> public class FlyWeightFactory { Dictionary<string, Chessman> _dicChessMan = new Dictionary<string, Chessman>(); public FlyWeightFactory() { _dicChessMan.Add("黑", new Chessman() { Color = "黑" }); _dicChessMan.Add("白", new Chessman() { Color = "白" }); } public Chessman GetChessman(string key) { return _dicChessMan[key]; } } public interface IFlyWeight { void Use(ChessmanPostion chessmanPostion); } /// <summary> /// 棋子 /// </summary> public class Chessman : IFlyWeight { public string Color { get; set; } public void Use(ChessmanPostion chessmanPostion) { Console.WriteLine($"{Color} X:{chessmanPostion.X} Y:{chessmanPostion.Y}"); } } /// <summary> /// 棋子位置(在这里棋子是外部状态) /// </summary> public class ChessmanPostion { public int X; public int Y; }
标签:享元,Chessman,模式,class,new,chessmanPostion,public,ChessmanPostion 来源: https://www.cnblogs.com/student-note/p/12469241.html