熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

Flyweight(享元)模式

2013-11-23 19:44:41  來源: Java高級技術 

  GOF運用共享技術有效地支持大量細粒度的對象

  解釋一下概念也就是說在一個系統中如果有多個相同的對象那麼只共享一份就可以了不必每個都去實例化一個對象比如說(這裡引用GOF書中的例子)一個文本系統每個字母定一個對象那麼大小寫字母一共就是那麼就要定義個對象如果有一個M的文本那麼字母是何其的多如果每個字母都定義一個對象那麼內存早就爆了那麼如果要是每個字母都共享一個對象那麼就大大節約了資源

  在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() 
 {
  Systemoutprintln(ConcreteFlyweight : + string);
 }
}

  實現一個工廠方法類

  

  public class FlyweightFactory
{
 private Hashtable flyweights = new Hashtable();
 public FlyweightFactory(){}
 public Flyweight getFlyWeight(Object obj)
 {
  Flyweight flyweight = (Flyweight) flyweightsget(obj)
  if(flyweight == null) {
   //產生新的ConcreteFlyweight
   flyweight = new ConcreteFlyweight((String)obj);
   flyweightsput(obj flyweight);
  }
  return flyweight;
 }
 public int getFlyweightSize() 
 {
  return flyweightssize();
 }
}

  最後看看Flyweight的調用

  

  public class FlyweightPattern {
 FlyweightFactory factory = new FlyweightFactory();
 Flyweight fly;
 Flyweight fly;
 Flyweight fly;
 Flyweight fly;
 Flyweight fly;
 Flyweight fly;
 /** *//** Creates a new instance of FlyweightPattern */
 public FlyweightPattern() {
  fly = factorygetFlyWeight(Google);
  fly = factorygetFlyWeight(Qutr);
  fly = factorygetFlyWeight(Google);
  fly = factorygetFlyWeight(Google);
  fly = factorygetFlyWeight(Google);
  fly = factorygetFlyWeight(Google);
 }
 public void showFlyweight()
 {
  flyoperation();
  flyoperation();
  flyoperation();
  flyoperation();
  flyoperation();
  flyoperation();
  int objSize = factorygetFlyweightSize();
  Systemoutprintln(objSize = + objSize);
 }
 public static void main(String[] args)
 {
  Systemoutprintln(The FlyWeight Pattern!);
  FlyweightPattern fp = new FlyweightPattern();
  fpshowFlyweight();
 }
}

  下面是運行結果

   ConcreteFlyweight : Google
ConcreteFlyweight : Qutr
ConcreteFlyweight : Google
ConcreteFlyweight : Google
ConcreteFlyweight : Google
ConcreteFlyweight : Google
objSize =


  我們定義了個對象其中有個是相同的按照Flyweight模式的定義Google應該共享一個對象在實際的對象數中我們可以看出實際的對象卻是只有


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27378.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.