享元模式(Flyweight Pattern)

      享元模式以共享的方式高效地支持大量的细粒度对象,说的再具体一些是将所有具有相同状态的对象指向同一个引用,从而解决了系统在创建大量对象时所带来的内存压力。
      享元模式应用较少,这里举一个森林和树木的例子来说明这个模式的应用。一片森林中有成千上万棵树木,如果每棵树都创建一个对象,那么内存中的对象数量相当庞大,更何况我们现实世界中还有成千上万个森林。

     public   class  App
    {
        
public   static   void  Main()
        {
            Forest forest 
=   new  Forest( " 国家森林 " );
            forest.trees.Add(TreeFactory.GetTree(
" 白杨 " 5 ));

            Forest forest2
= new  Forest( " 自然森林 " );
            forest2.trees.Add(TreeFactory.GetTree(
" 白杨 " , 6 ));
            forest2.trees.Add(TreeFactory.GetTree(
" 白杨 " , 5 ));

            
if (ReferenceEquals(forest.trees[ 0 ],forest2.trees[ 1 ])) Console.WriteLine( " 内存中指的是同一棵树 " );

            Console.ReadLine();
        }
    }

    
public   class  Tree
    {
        
string  type;
        
int  age;

        
public  Tree( string  tType, int  tAge)
        {
            
this .type  =  tType;
            
this .age  =  tAge;
        }
    }

    
public   static   class  TreeFactory
    {
        
private   static  Hashtable existTrees  =   new  Hashtable();

        
public   static  Tree GetTree( string  treeType,  int  treeAge)
        {
            
if  ( ! existTrees.ContainsKey(treeType + treeAge))
            {
                existTrees.Add(treeType 
+  treeAge,  new  Tree(treeType, treeAge));
            }

            
return  existTrees[treeType  +  treeAge]  as  Tree;
        }
    }

    
public   class  Forest
    {
        
string  name;
        
public  List < Tree >  trees {  get set ; }

        
public  Forest( string  name)
        {
            
this .name  =  name;
            trees 
=   new  List < Tree > ();
        }
    }

转载于:https://www.cnblogs.com/binfen/archive/2009/07/26/1531438.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值