【C#】Structural Patterns Flyweight Mode

The Flyweight design pattern uses sharing to support large numbers of fine-grained objects efficiently.


简单来说~ Flyweight模式使用共享来提供大量的细节对象


学习目标: 享元模式的概念及实务

学习难度: ☆☆☆


using System;using System.Collections.Generic;namespace ConsoleApp{    //建立一个生产game的工厂    public class GameFactory    {        public Game GetGame(string factory) //回传Game物件        {            Game game = null;            if (factory == "Ensemble")            {                game = new AOE();            }            else if (factory == "VALVE")            {                game = new CSGO();            }            return game;        }    }    //建立一个抽象类,用于定义物件的细节    public abstract class Game    {        protected string type;        protected string name;        public string version;        public int price;        public abstract void Demo();    }    //实作物件1    public class AOE : Game    {        // Constructor        public AOE()        {            type = "RTS";            name = "AOE3";            version = "1.0";            price = 250;        }        public override void Demo()        {            Console.WriteLine(" Create " + this.GetType().Name + " Game " + "And the Game's version is " + version);        }    }    //实作物件2    public class CSGO : Game    {        // Constructor        public CSGO()        {            type = "FPS";            name = "CSGO";            version = "1.0";            price = 200;        }        public override void Demo()        {            Console.WriteLine(" Create " + this.GetType().Name + " Game " + "And the Game's version is " + version);        }    }    public class MainProgram    {        public static void Main(string[] args)        {            GameFactory factory = new GameFactory();            string factory1 = "Ensemble";            Game aoe = factory.GetGame(factory1);            aoe.version = "2.0";            aoe.Demo();            string factory2 = "VALVE";            Game csgo = factory.GetGame(factory2);            csgo.version = "2.0";            csgo.Demo();        }    }}

参考资料:

https://www.dofactory.com/net/flyweight-design-pattern


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章