java23种设计模式之共享模式(FlyWeight)

 http://www.0755build.com

共享模式(FlyWeight)避免拥有相同内容的小类的开销(如耗费内存),使大家同享一个类(元类)。为什么使用共享模式(FlyWeight)呢?因为面向对象语言的原则就是一切都是对象,但是如果真正使用起来,有时对象数可能显得很庞大,比如字处理软件,如果每个文字都作为一个对象,几千个字就是几千个对象,无疑会耗费内存,所以我们要“求同存异”,找出这些对象群的共同点,设计一个元类。共享模式(Flyweight)有两个重要的概念内部状态intrinsic和外部状态extrinsic,它能提高程序的效率和性能,大大加快程序的运行速度。共享模式(Flyweight)的实现如下:

package yw.flyweight;
//共享池
public interface Flyweight {
 public void operation(ExtrinsicStat state);
}

package yw.flyweight;
//用于本模式的抽象数据类型(根据自己的要求设计)
public interface ExtrinsicStat {

}


package yw.flyweight;

public interface IntrinsicState {

}

package yw.flyweight;
//共享的
public class ConcreateFlyweight implements Flyweight{
 private IntrinsicState state;
 public void operation(ExtrinsicStat state) {
  //具体操作
 }

}

 

package yw.flyweight;
//不共享的
public class UnsharedConcreateFlyweight implements Flyweight{

 public void operation(ExtrinsicStat state) {
  
 }

}

 

package yw.flyweight;

import java.util.Hashtable;

public class FlyweightFactory {
 private Hashtable flyweights=new Hashtable();
 public Flyweight getFlyweight(Object key){
  Flyweight flyweight=(Flyweight)flyweights.get(key);
  if(flyweight==null){
   //产生新的ConcreateFlyweight
   flyweight=new ConcreateFlyweight();
   flyweights.put(key, flyweight); //将该对象加入到共享池总
  }
  return flyweight;
 }
}

 

package yw.flyweight;

public class FlyweightApp {
 public static void main(String args[]){
  FlyweightFactory factory=new FlyweightFactory();
  Flyweight fly1=factory.getFlyweight("Object1");
  Flyweight fly2=factory.getFlyweight("Object2");
  Flyweight fly3=factory.getFlyweight("Object2");
  //当大量的调用Flyweight对象时,肯定有重复调用的情况,所以我们就可以少创建很多对象,直接从共享池中取得该对象
 }
}

使用实例,以CD为例子,我们假设在一个XML文件中,存放多个CD资料,每个CD有三个字段,1:出片日期;2:歌唱者姓名等信息;3:唱片曲目

CD就好比Flyweight

public class CD{

private String title;

private int year;

private Artist artist;

...

}

以Aritist作为共享的ConcreateFlyweight

public class Aritist{

private String name;

public Artist(String n){

name=n;

}

public String getName(){

return name;

}

}

在看看Flyweight factory专门用来制造上面的可共享的ConcreateFlyweight:Artist

public class FlyweightFactory{

Hashtable pool=new Hashtable();

Artist getArtist(String key){

Artist result=(Artist)pool.get(key);

if(result==null){

result=new Artist(key);

pool.put(key,result);

}

return result;

}

}

所以如果有大量的CD,Flyweight将大大的节省了空间。

阅读更多
个人分类: java 设计模式 java
上一篇java23种设计模式之原型模式(Prototype)
下一篇Jquery的api中提供了对元素应用disabled和readonly属性的方法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭