Flyweight 享元模式

 public class Font    //12+8 bytes  8用于垃圾手机
    {
        string fontName;  //4 bytes
        int size;         //4 bytes 
        Color color;      //4 bytes

        public Font( string fontName, int size, Color color )
        {
            this.fontName = fontName;
            this.size = size;
            this.color = color;
        }

        public override bool Equals( object obj )
        {
            return base.Equals( obj );
        }
    }
    public class Color
    {
    }
 public class Charactor   //(2+4+20+2)+8 byes =36 bytes  8 bytes用于垃圾收集
    {
        char c;    //2 bytes
        //Font f;    //20 bytes
    //重点就在于下面的实现
private static Hashtable fontTable = new Hashtable(); public void SetFont( String name, int size, Color color ) { if( fontTable.ContainsKey( name ) ) { return; } else { Font f = new Font( name, size, color ); fontTable.Add( name,f ); } } }

其实主要就是为了降低内存,对一些固定不变的东西做一个共享,经常变换的不做考虑,在.net里面字符串就是做了享元处理,codebehid也是享元模式的一个处理

posted on 2013-04-08 09:43  HOT SUMMER  阅读(150)  评论(0编辑  收藏  举报

导航