免费注册 查看新帖 |

Chinaunix

广告
  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1050 | 回复: 0
打印 上一主题 下一主题

Flyweight(享元)模式 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-12-02 16:54 |只看该作者 |倒序浏览
GOF:运用共享技术有效地支持大量细粒度的对象。
  解释一下概念:也就是说在一个系统中如果有多个相同的对象,那么只共享一份就可以了,不必每个都去实例化一个对象。比如说(这里引用GOF书中的例子)一个文本系统,每个字母定一个对象,那么大小写字母一共就是52个,那么就要定义52个对象。如果有一个1M的文本,那么字母是何其的多,如果每个字母都定义一个对象那么内存早就爆了。那么如果要是每个字母都共享一个对象,那么就大大节约了资源。
  在Flyweight模式中,由于要产生各种各样的对象,所以在Flyweight(享元)模式中常出现Factory模式。Flyweight的内部状态是用来共享的,Flyweight factory负责维护一个对象存储池(Flyweight Pool)来存放内部状态的对象。Flyweight模式是一个提高程序效率和性能的模式,会大大加快程序的运行速度.应用场合很多,下面举个例子:

先定义一个抽象的Flyweight类:
public abstract class Flyweight
{
 public abstract void operation();
}
在实现一个具体类:
public class ConcreteFlyweight extends Flyweight
{
 private String string;
 public ConcreteFlyweight(String str) 
 {
  string = str;
 }
 public void operation() 
 {
  System.out.println("Concrete---Flyweight : " + string);
 }
}
实现一个工厂方法类:
public class FlyweightFactory
{
 private Hashtable flyweights = new Hashtable();
 public FlyweightFactory(){}
 public Flyweight getFlyWeight(Object obj)
 {
  Flyweight flyweight = (Flyweight) flyweights.get(obj)
  if(flyweight == null) ...{
   //产生新的ConcreteFlyweight
   flyweight = new ConcreteFlyweight((String)obj);
   flyweights.put(obj, flyweight);
  }
  return flyweight;
 }
 public int getFlyweightSize() 
 {
  return flyweights.size();
 }
}
最后看看Flyweight的调用:
public class FlyweightPattern {
 FlyweightFactory factory = new FlyweightFactory();
 Flyweight fly1;
 Flyweight fly2;
 Flyweight fly3;
 Flyweight fly4;
 Flyweight fly5;
 Flyweight fly6;
 /** *//** Creates a new instance of FlyweightPattern */
 public FlyweightPattern() {
  fly1 = factory.getFlyWeight("Google");
  fly2 = factory.getFlyWeight("Qutr");
  fly3 = factory.getFlyWeight("Google");
  fly4 = factory.getFlyWeight("Google");
  fly5 = factory.getFlyWeight("Google");
  fly6 = factory.getFlyWeight("Google");
 }
 public void showFlyweight()
 {
  fly1.operation();
  fly2.operation();
  fly3.operation();
  fly4.operation();
  fly5.operation();
  fly6.operation();
  int objSize = factory.getFlyweightSize();
  System.out.println("objSize = " + objSize);
 }
 public static void main(String[] args)
 {
  System.out.println("The FlyWeight Pattern!");
  FlyweightPattern fp = new FlyweightPattern();
  fp.showFlyweight();
 }
}
下面是运行结果:
Concrete---Flyweight : Google
Concrete---Flyweight : Qutr
Concrete---Flyweight : Google
Concrete---Flyweight : Google
Concrete---Flyweight : Google
Concrete---Flyweight : Google
objSize = 2

我们定义了6个对象,其中有5个是相同的,按照Flyweight模式的定义“Google”应该共享一个对象,在实际的对象数中我们可以看出实际的对象却是只有2个


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/76927/showart_1675888.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP