设计模式袖珍版 连续转载之 - Flyweight(享元)

<script language="javascript" type="text/javascript"> showbanner(6,6,1); </script><script type="text/javascript"> google_ad_client ="pub-2141342037947367";google_ad_width = 120;google_ad_height =240;google_ad_format = "120x240_as";google_ad_channel="8570654326";google_color_border = "CCCCCC";google_color_bg ="FFFFFF";google_color_link = "000000";google_color_url ="666666";google_color_text = "333333"; </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-2141342037947367&dt=1117558825515&lmt=1117558825&prev_fmts=468x60_pas_abgnc&format=120x240_as&output=html&channel=8570654326&url=http%3A%2F%2Fwww.javaresearch.org%2Farticle%2Fshowarticle.jsp%3Fcolumn%3D31%26thread%3D12460&color_bg=FFFFFF&color_text=333333&color_link=000000&color_url=666666&color_border=CCCCCC&ref=http%3A%2F%2Fwww.javaresearch.org%2Farticle%2Fallarticles.jsp%3Fstart%3D720%26thRange%3D30&cc=476&u_h=768&u_w=1024&u_ah=740&u_aw=1024&u_cd=16&u_tz=480&u_java=true" frameborder="0" width="120" scrolling="no" height="240" allowtransparency="65535">
原作:fanix

Flyweight定义:
避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类).

为什么使用?
面向对象语言的原则就是一切都是对象,但是如果真正使用起来,有时对象数可能显得很庞大,比如,字处理软件,如果以每个文字都作为一个对象,几千个字,对象数就是几千,无疑耗费内存,那么我们还是要"求同存异",找出这些对象群的共同点,设计一个元类,封装可以被共享的类,另外,还有一些特性是取决于应用(context),是不可共享的,这也Flyweight中两个重要概念内部状态intrinsic和外部状态extrinsic之分.

说白点,就是先捏一个的原始模型,然后随着不同场合和环境,再产生各具特征的具体模型,很显然,在这里需要产生不同的新对象,所以Flyweight模式中常出现Factory模式.Flyweight的内部状态是用来共享的,Flyweight factory负责维护一个Flyweight pool(模式池)来存放内部状态的对象.

Flyweight模式是一个提高程序效率和性能的模式,会大大加快程序的运行速度.应用场合很多:比如你要从一个数据库中读取一系列字符串,这些字符串中有许多是重复的,那么我们可以将这些字符串储存在Flyweight池(pool)中.

如何使用?


我们先从Flyweight抽象接口开始:

程序代码:

  1. public interface Flyweight 
  2. {
  3.   public void operation( ExtrinsicState state );
  4. }
  5. //用于本模式的抽象数据类型(自行设计)
  6. public interface ExtrinsicState { }

 

下面是接口的具体实现(ConcreteFlyweight) ,并为内部状态增加内存空间, ConcreteFlyweight必须是可共享的,它保存的任何状态都必须是内部(intrinsic),也就是说,ConcreteFlyweight必须和它的应用环境场合无关.
程序代码:

  1. public class ConcreteFlyweight implements Flyweight {
  2.   private IntrinsicState state; 
  3.   
  4.   public void operation( ExtrinsicState state ) 
  5.   { 
  6.       //具体操作
  7.   } 

 

当然,并不是所有的Flyweight具体实现子类都需要被共享的,所以还有另外一种不共享的ConcreteFlyweight:
程序代码:

  1. public class UnsharedConcreteFlyweight implements Flyweight {
  2.   public void operation( ExtrinsicState state ) { }
  3. }
  4.  


Flyweight factory负责维护一个Flyweight池(存放内部状态),当客户端请求一个共享Flyweight时,这个factory首先搜索池中是否已经有可适用的,如果有,factory只是简单返回送出这个对象,否则,创建一个新的对象,加入到池中,再返回送出这个对象.池

程序代码:

  1. public class FlyweightFactory { 
  2.   //Flyweight pool
  3.   private Hashtable flyweights = new Hashtable(); 
  4.   public Flyweight getFlyweight( Object key ) { 
  5.     Flyweight flyweight = (Flyweight) flyweights.get(key); 
  6.     if( flyweight == null ) {
  7.       //产生新的ConcreteFlyweight
  8.       flyweight = new ConcreteFlyweight(); 
  9.       flyweights.put( key, flyweight ); 
  10.     } 
  11.     return flyweight; 
  12.   } 
 

至此,Flyweight模式的基本框架已经就绪,我们看看如何调用:
程序代码:

  1. FlyweightFactory factory = new FlyweightFactory(); 
  2. Flyweight fly1 = factory.getFlyweight( "Fred" ); 
  3. Flyweight fly2 = factory.getFlyweight( "Wilma" );
  4. ......


从调用上看,好象是个纯粹的Factory使用,但奥妙就在于Factory的内部设计上.

Flyweight模式在XML等数据源中应用
我们上面已经提到,当大量从数据源中读取字符串,其中肯定有重复的,那么我们使用Flyweight模式可以提高效率,以唱片CD为例,在一个XML文件中,存放了多个CD的资料.

每个CD有三个字段:
1.出片日期(year)
2.歌唱者姓名等信息(artist)
3.唱片曲目 (title)

其中,歌唱者姓名有可能重复,也就是说,可能有同一个演唱者的多个不同时期 不同曲目的CD.我们将"歌唱者姓名"作为可共享的ConcreteFlyweight.其他两个字段作为UnsharedConcreteFlyweight.

首先看看数据源XML文件的内容:

程序代码:

<?xml version="1.0"?>
<collection>


<cd>
<title>Another Green World</title>
<year>1978</year>
<artist>Eno, Brian</artist>
</cd>


<cd>
<title>Greatest Hits</title>
<year>1950</year>
<artist>Holiday, Billie</artist>
</cd>


<cd>
<title>Taking Tiger Mountain (by strategy)</title>
<year>1977</year>
<artist>Eno, Brian</artist>
</cd>


....... 

</collection>

 


虽然上面举例CD只有3张,CD可看成是大量重复的小类,因为其中成分只有三个字段,而且有重复的(歌唱者姓名).

CD就是类似上面接口 Flyweight:

程序代码:

  1. public class CD {
  2.   private String title;
  3.   private int year;
  4.   private Artist artist;
  5.   public String getTitle() {  return title; }
  6.   public int getYear() {    return year;  }
  7.   public Artist getArtist() {    return artist;  }
  8.   public void setTitle(String t){    title = t;}
  9.   public void setYear(int y){year = y;}
  10.   public void setArtist(Artist a){artist = a;}
  11. }
  12.  


将"歌唱者姓名"作为可共享的ConcreteFlyweight:
程序代码:

  1. public class Artist {
  2.   //内部状态
  3.   private String name; 
  4.   // note that Artist is immutable.
  5.   String getName(){return name;}
  6.   Artist(String n){
  7.     name = n;
  8.   } 
  9. }

 

再看看Flyweight factory,专门用来制造上面的可共享的ConcreteFlyweight:Artist
程序代码:

  1. public class ArtistFactory {
  2.   Hashtable pool = new Hashtable();
  3.   Artist getArtist(String key){
  4.     Artist result;
  5.     result = (Artist)pool.get(key);
  6.     产生新的Artist
  7.     if(result == null) {
  8.       result = new Artist(key);
  9.       pool.put(key,result);
  10.       
  11.     }
  12.     return result;
  13.   }
  14. }

 

当你有几千张甚至更多CD时,Flyweight模式将节省更多空间,共享的flyweight越多,空间节省也就越大.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值