天天看點

極速了解設計模式系列:14.輕量級模式(Flyweight Pattern)

五個角色:抽象輕量級類(Flyweight)、具體輕量級類(ConcreteFlyweight)、不共享具體輕量級類(UnsharedConcreteFlyweight)、輕量級類工廠(FlyweightFactory)、用戶端(Client) 

        抽象輕量級類(Flyweight):聲明一個接口并且有一些屬性可以設定對象的狀态

        具體輕量級類(ConcreteFlyweight):實作接口,并且有相關的狀态

        不共享具體輕量級類(UnsharedConcreteFlyweight):不被共享的具體輕量級類

        輕量級類工廠(FlyweightFactory):建立并且管理Flyweight對象,當用戶端發出輕量級類請求時提供一個已建立或者未建立的對象

        用戶端(Client) :隻需要使用輕量級類工廠調用相應的輕量級類即可。

 實作思路:用戶端調用輕量級類工廠,工廠去查找是否已經有輕量級類執行個體,如果有則直接傳回給用戶端,如果沒有則根據條件建立相應的執行個體給用戶端。

 類圖:

<a target="_blank" href="http://blog.51cto.com/attachment/201204/163712996.gif"></a>

應用場景:遊戲中的衣服實對象有很多種,會背穿在很多人的身上。

分析:遊戲中的衣服它穿在很多人的身上,如果為每個人身上的衣服設定一個執行個體,那麼對伺服器的壓力将不言而喻,這時如果在衣服内部設定很多種狀态屬性,在用戶端調用的時候,使用輕量級類工廠來建立選擇即可。

        下面我們在控制台程式去示範一下如何使用Flyweight Pattern:

        一、抽象輕量級類(Flyweight)

//抽象輕量級類(Flyweight) 

abstract class Clothes 

    public string Name { get; set; } 

    public int Defense { get; set; } 

    public abstract void GetDefense(); 

        二、具體輕量級類(ConcreteFlyweight)

//具體輕量級類(ConcreteFlyweight) 

class LowClothes : Clothes 

    public LowClothes() 

    { 

        Name = "青銅聖衣"; 

        Defense = 50; 

    } 

    public override void GetDefense() 

        Console.WriteLine(Name + "的防禦是" + Defense); 

class MiddleClothes : Clothes 

    public MiddleClothes() 

        Name = "白銀聖衣"; 

        Defense = 80; 

class HighClothes : Clothes 

    public HighClothes() 

        Name = "黃金聖衣"; 

        Defense = 100; 

        三、輕量級類工廠(FlyweightFactory)

//輕量級類工廠(FlyweightFactory) 

class ClothesFactory 

    private Hashtable clothesHT = new Hashtable(); 

    public Clothes GetClothes(string clothesName) 

        Clothes clothes = (Clothes)clothesHT[clothesName]; 

        if (clothes == null) 

        { 

            switch (clothesName) 

            { 

                case "青銅聖衣": clothes = new LowClothes(); 

                    break; 

                case "白銀聖衣": clothes = new MiddleClothes(); 

                case "黃金聖衣": clothes = new HighClothes(); 

            } 

            clothesHT.Add(clothesName, clothes); 

        } 

        return clothes; 

        四、用戶端(Client) 

//用戶端(Client) 

class Program 

    static void Main(string[] args) 

        ClothesFactory fac = new ClothesFactory(); 

        fac.GetClothes("黃金聖衣").GetDefense(); 

        fac.GetClothes("白銀聖衣").GetDefense(); 

        fac.GetClothes("青銅聖衣").GetDefense(); 

        Console.ReadLine(); 

本文轉自程興亮 51CTO部落格,原文連結:http://blog.51cto.com/chengxingliang/827013

繼續閱讀