设计模式学习笔记——享元模式(Flyweight)

1.特点:为运用共享技术,支持大量细粒度对象,节省开销。

2.概念:运用共享技术有效地支持大量细粒度的对象。

3.类图:

    public abstract class Character
    {
        public int Size { get; set; }
        public Color Color { get; set; }
        protected char _c;

        public Character()
        {
            Size = 10;
            Color = Color.Black;
        }

        public override string ToString()
        {
            return string.Format("Character is {0}, Size is {1}, Color is {2}", _c, Size.ToString(), Color.ToString());
        }
    }
    public class CharacterA : Character
    {
        public CharacterA()
        {
            _c = 'A';
        }
    }

    public class CharacterB : Character
    {
        public CharacterB()
        {
            _c = 'B';
        }
    }

    public class CharacterC : Character
    {
        public CharacterC()
        {
            _c = 'C';
        }
    }
    public static class CharacterFactory
    {
        private static Dictionary<char, Character> _characters;

        static CharacterFactory()
        {
            _characters = new Dictionary<char, Character>();
            _characters.Add('a', new CharacterA());
            _characters.Add('b', new CharacterB());
            _characters.Add('c', new CharacterC());
        }

        public static Character GetCharacter(char c)
        {
            return _characters[c];
        }
    }
    static void Main(string[] args)
    {
        Character character = CharacterFactory.GetCharacter('a');
        Console.WriteLine(character.ToString());
        character = CharacterFactory.GetCharacter('b');
        character.Size = 20;
        character.Color = Color.Red;
        Console.WriteLine(character.ToString());
        character = CharacterFactory.GetCharacter('c');
        character.Size = 15;
        character.Color = Color.Yellow;
        Console.WriteLine(character.ToString());
    }

  

posted @ 2015-08-07 12:10  ice_baili  阅读(184)  评论(0编辑  收藏  举报