Flyweight享元模式

时间:2021-02-16 23:01:00 来源:互联网 作者: 神秘的大神 字体:

>>返回《C#常用设计模式》

  • 1. 简介
  • 2. 示例

1. 简介

  • 定义
    • 使用共享对象可有效地支持大量的细粒度的对象。
  • 解决问题
    • 面向对象技术可以很好地解决一些灵活性或可扩展性问题,但在很多情况下需要在系统中增加类和对象的个数。当对象数量太多时,将导致运行代价过高,带来性能下降等问题。享元模式正是为解决这一类问题而诞生的。
  • 原理
    • 享元模式其实就是工厂模式的一个改进机制,享元模式同样要求创建一个或一组对象,并且就是通过工厂方法生成对象的,只不过享元模式中为工厂方法增加了缓存这一功能。
  • 类图
  • 典型的例子,如:string对象,Type对象等,都是使用享元模式设计。

2. 示例

/// <summary>
/// The 'Flyweight' class.
/// </summary>
public class Character
{
    // intrinsic state
    protected char _symbol;
    protected int _size;
    protected string _font;
    // extrinsic state
    protected Position _position;

    public void Display(Position position)
    {
        Console.WriteLine(
            String.Format("Symbol: {0} Size: {1} Font: {2} Position: {3} {4}",
            _symbol, _size, _font, position._x, position._y));
    }

}

/// <summary>
/// A 'ConcreteFlyweight' class
/// </summary>
public class CharacterA : Character
{
    public CharacterA()
    {
        _symbol = 'A';
        _size = 10;
        _font = "宋体";
        //_position = new Position(0, 1);
    }
}

/// <summary>
/// The 'FlyweightFactory' class
/// </summary>
public class CharacterFactory
{
    // Keeps the character object by specifying key/value.
    private Dictionary<char, Character> _characters =
        new Dictionary<char, Character>();

    public Character this[char key]
    {
        get
        {
            Character character = null;
            // Checked the character whether existed or not,
            // if the character existed, then directly returns,
            // otherwise, instantiates a character object.
            if (_characters.ContainsKey(key))
            {
                character = _characters[key];
            }
            else
            {
                string name = this.GetType().Namespace + "." +
                              "Character" + key.ToString();
                    character = Activator.CreateInstance(
                        Type.GetType(name)) as Character;
                _characters.Add(key, character);
            }
            return character;
        }
    }
}

/// <summary>
/// The client.
/// </summary>
/// <param name="args">The args.</param>
static void Main(string[] args)
{
    string text = "ABZABBZZ";
    char[] letters = text.ToCharArray();

    var characterFactory = new CharacterFactory();

    // Creates random position ranges 0 to 100.
    var rd = new Random();

    foreach (char c in letters)
    {
        Character character = characterFactory[c];
        var p = new Position(rd.Next(0, 100), rd.Next(0, 100));
        character.Display(p);
    }
    Console.ReadKey();
}