码迷,mamicode.com
首页 > Windows程序 > 详细

享元模式 c#

时间:2016-01-08 22:05:14      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

  我们写文档的时候不可能对每一个字符都进行内存分配,只需要对基本字符分配内存然后进行复用就可以了。

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {

        public abstract class Character
        {
            private int size;
            private string color;
            public char c;

            public int Size
            {
                get { return size; }
                set { size = value; }
            }

            public string Color
            {
                get { return color; }
                set { color = value; }
            }

            public Character()
            {
                Size = 10;
                Color = "red";
            }

            public override string ToString()
            {
                return string.Format("C: {0}, Color: {1}, Size: {2}", c, color, size);
            }
        }

        public class CharacterA : Character
        {
            public CharacterA()
            {
                c = c;
            }
        }

        public class CharacterB : Character
        {
            public CharacterB()
            {
                c = b;
            }


        }


        public class FlyweightCharacter
        {
            private Dictionary<char, Character> characters;

            public Character GetCharacter(char c)
            {
                Character charact;
                if (characters.TryGetValue(c, out charact))
                {
                    return charact;
                }
                else
                {
                    return null;
                }

            }

            private FlyweightCharacter()
            {
                characters = new Dictionary<char, Character>();
                characters.Add(a, new CharacterA());
                characters.Add(b, new CharacterB());
            }

            private static FlyweightCharacter instance;

            public static FlyweightCharacter Instance
            {
                get
                {
                    if (instance == null)
                    {
                        instance = new FlyweightCharacter();
                    }

                    return instance;
                }
                set { instance = value; }
            }
        }

        static void Main(string[] args)
        {
            Character character = FlyweightCharacter.Instance.GetCharacter(a);
            Console.WriteLine(character.ToString());

        }
    }
}

 

享元模式 c#

标签:

原文地址:http://www.cnblogs.com/zkzk945/p/5114662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!