iT邦幫忙

0

【C#】Structural Patterns Flyweight Mode

c#
  • 分享至 

  • xImage
  •  

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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言