站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题设计模式之Flyweight

设计模式之Flyweight

摘要: 面向对象语言的原则就是一切都是对象,但是如果真正使用起来,有时对象数可能显得很庞大......
<iframe align=right marginWidth=0 marginHeight=0 src="http://www.chinabyte.com/tag/cont_flash_software.html" frameBorder=0 width=360 scrolling=no height=300></iframe>  Flyweight定义:

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

  为什么使用?

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

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

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

  如何使用?

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

<table cellSpacing=0 cellPadding=0 width=600 bgColor=#ffffff border=0> <tr> <td>public interface Flyweight
{
  public void operation( ExtrinsicState state );
}

//用于本模式的抽象数据类型(自行设计)
public interface ExtrinsicState { } </td></tr></table>
  下面是接口的具体实现(ConcreteFlyweight) ,并为内部状态增加内存空间, ConcreteFlyweight必须是可共享的,它保存的任何状态都必须是内部(intrinsic),也就是说,ConcreteFlyweight必须和它的应用环境场合无关.

<table cellSpacing=0 cellPadding=0 width=600 bgColor=#ffffff border=0> <tr> <td>public class ConcreteFlyweight implements Flyweight {
  private IntrinsicState state;
  
  public void operation( ExtrinsicState state )
  {
      //具体操作
  }
} </td></tr></table>
  当然,并不是所有的Flyweight具体实现子类都需要被共享的,所以还有另外一种不共享的ConcreteFlyweight:

<table cellSpacing=0 cellPadding=0 width=600 bgColor=#ffffff border=0> <tr> <td>public class UnsharedConcreteFlyweight implements Flyweight {

  public void operation( ExtrinsicState state ) { }

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

<table cellSpacing=0 cellPadding=0 width=600 bgColor=#ffffff border=0> <tr> <td>public class FlyweightFactory {
  //Flyweight pool
  private Hashtable flyweights = new Hashtable();

  public Flyweight getFlyweight( Object key ) {


    Flyweight flyweight = (Flyweight) flyweights.get(key);


    if( flyweight == null ) {
      //产生新的ConcreteFlyweight
      flyweight = new ConcreteFlyweight();
      flyweights.put( key, flyweight );
    }


    return flyweight;
  }
} </td></tr></table>
  至此,Flyweight模式的基本框架已经就绪,我们看看如何调用:

<table cellSpacing=0 cellPadding=0 width=600 bgColor=#ffffff border=0> <tr> <td>FlyweightFactory factory = new FlyweightFactory();
Flyweight fly1 = factory.getFlyweight( "Fred" );
Flyweight fly2 = factory.getFlyweight( "Wilma" );
...... </td></tr></table>
  从调用上看,好象是个纯粹的Factory使用,但奥妙就在于Factory的内部设计上。




↑返回目录
前一篇: Jini技术基础结构
后一篇: 解析JBuilder数据库应用程序