天天看點

Net設計模式執行個體之享元模式( Flyweight Pattern)(2)

一個文檔Document中隻有少數字元需要共享。結構如下圖所示

CharacterFactory類,享元工廠,用來建立和管理Charactor對象。如果請求的Charactor對象存在,怎傳回已經存在的對象。否則新建立一個新的對象傳回。

Character類:享元抽象類,通過這個接口,Character可以接受并作用與外部狀态。

CharacterA /CharacterB/CharacterC 類:實作享元抽象類,為内部狀态添加存儲空間。

1、字元工廠類CharacterFactory

class CharacterFactory

{

    private Dictionary<char, Character> _characters = new Dictionary<char, Character>();

    public Character GetCharacter(char key)

    {

        // Uses "lazy initialization"

        Character character = null;

        if (_characters.ContainsKey(key))

        {

            character = _characters[key];

        }

        else

            switch (key)

            {

                case 'A': character = new CharacterA(); break;

                case 'B': character = new CharacterB(); break;

                //...

                case 'Z': character = new CharacterZ(); break;

            }

            _characters.Add(key, character);

        return character;

    }

}

2、抽象資料對象類DataObject及其具體實作類CustomersData

/// <summary>

/// The 'Flyweight' abstract class

/// </summary>

abstract class Character

    protected char symbol;

    protected int width;

    protected int height;

    protected int ascent;

    protected int descent;

    protected int pointSize;

    public abstract void Display(int pointSize);

/// A 'ConcreteFlyweight' class

class CharacterA : Character

    public CharacterA()

        this.symbol = 'A';

        this.height = 100;

        this.width = 120;

        this.ascent = 70;

        this.descent = 0;

    public override void Display(int pointSize)

        this.pointSize = pointSize;

        Console.WriteLine(this.symbol + " (pointsize " + this.pointSize + ")");

class CharacterB : Character

    public CharacterB()

        this.symbol = 'B';

        this.width = 140;

        this.ascent = 72;

// ... C, D, E, etc.

class CharacterZ : Character

    // Constructor

    public CharacterZ()

        this.symbol = 'Z';

        this.width = 100;

        this.ascent = 68;

        Console.WriteLine(this.symbol +" (pointsize " + this.pointSize + ")");

3、用戶端代碼

static void Main(string[] args)

    // Build a document with text

    string document = "AAZZBBZB";

    char[] chars = document.ToCharArray();

    CharacterFactory factory = new CharacterFactory();

    // extrinsic state

    int pointSize = 10;

    // For each character use a flyweight object

    foreach (char c in chars)

        pointSize++;

        Character character = factory.GetCharacter(c);

        character.Display(pointSize);

    Console.ReadKey();

本文對享元模式(Flyweight Pattern)的概念、設計結構圖、代碼、使用場景、進行了描述。以一個享元模式執行個體進行了說明。如果一個應用程式使用了大量的對象,而大量的這些對象造成了很大的存儲開銷,這時可以考慮使用享元模式。

本文轉自 靈動生活 51CTO部落格,原文連結:http://blog.51cto.com/smartlife/269010,如需轉載請自行聯系原作者

繼續閱讀