【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


<<:  【C#】Behavioral Patterns Mediator Mode

>>:  烦请各位 excel 先进帮忙~感恩!!

这些日子我学到的JavaScript:Day26- BOM

BOM,是 JavaScript 与浏览器沟通的桥梁,JavaScript 可以透过 BOM 对浏览...

死结(Deadlock)是开发人员进行结对编程(pair programming)时,是最难发现的问题。

-XP 实践(来源:https ://twitter.com/CharlotteBRF ) 结对编...

Day 16 生命周期

我们常常在新增一个专案後会看到下面有个叫做viewDidLoad()的东西,如下图 viewDidL...

前端工程学习日记第17天

#伪类:before :after做左右画线标题效果 经常可以看到这样的标题设计是在左右有一条横线中...

e.stopPropagation()停止事件冒泡

当事件发生的时候,如果想要阻挡事件向上传递,只要利用「事件物件」(Event Object)所提供...