標籤:
Flyweight定義:避免大量擁有相同內容的小類的開銷(如耗費記憶體),使大家共用一個類(元類)。為什麼使用共用模式/享元模式物件導向語言的原則就是一切都是對象,但是如果真正使用起來,有時對象數可能顯得很龐大,比如,文書處理軟體,如果以每個文字都作為一個對象,幾千個字,對象數就是幾千,無疑耗費記憶體,那麼我們還是要"求同存異",找出這些對象群的共同點,設計一個元類,封裝可以被共用的類,另外,還有一些特性是取決於應用(context),是不可共用的,這也Flyweight中兩個重要概念內部狀態intrinsic和外部狀態extrinsic之分。
說白點,就是先捏一個的原始模型,然後隨著不同場合和環境,再產生各具特徵的具體模型,很顯然,在這裡需要產生不同的新對象,所以Flyweight模式中常出現Factory模式。Flyweight的內部狀態是用來共用的,Flyweight factory負責維護一個Flyweight pool(模式池)來存放內部狀態的對象。
Flyweight模式是一個提高程式效率和效能的模式,會大大加快程式的運行速度。應用場合很多:比如你要從一個資料庫中讀取一系列字串,這些字串中有許多是重複的,那麼我們可以將這些字串儲存在Flyweight池(pool)中。如何使用共用模式/享元模式我們先從Flyweight抽象介面開始:
public interface Flyweight{
public void operation( ExtrinsicState state );
}
//用於本模式的抽象資料類型(自行設計)
public interface ExtrinsicState { }
下面是介面的具體實現(ConcreteFlyweight),並為內部狀態增加記憶體空間,ConcreteFlyweight必須是可共用的,它儲存的任何狀態都必須是內部(intrinsic),也就是說,ConcreteFlyweight必須和它的應用環境場合無關。
public class ConcreteFlyweight implements Flyweight {
private IntrinsicState state;
public void operation( ExtrinsicState state ){
//具體操作
}
}
當然,並不是所有的Flyweight具體實現子類都需要被共用的,所以還有另外一種不共用的ConcreteFlyweight:
public class UnsharedConcreteFlyweight implements Flyweight {
public void operation( ExtrinsicState state ) { }
}
Flyweight factory負責維護一個Flyweight池(存放內部狀態),當用戶端請求一個共用Flyweight時,這個factory首先搜尋池中是否已經有可適用的,如果有,factory只是簡單返回送出這個對象,否則,建立一個新的對象,加入到池中,再返回送出這個對象池。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;
}
}至此,Flyweight模式的基本架構已經就緒,我們看看如何調用:
FlyweightFactory factory = new FlyweightFactory();
Flyweight fly1 = factory.getFlyweight( "Fred" );
Flyweight fly2 = factory.getFlyweight( "Wilma" );
......
從調用上看,好象是個純粹的Factory使用,但奧妙就在於Factory的內部設計上。Flyweight模式在XML等資料來源中應用我們上面已經提到,當大量從資料來源中讀取字串,其中肯定有重複的,那麼我們使用Flyweight模式可以提高效率,以唱片CD為例,在一個XML檔案中,存放了多個CD的資料。
每個CD有三個欄位:
- 出片日期(year)
- 歌唱者姓名等資訊(artist)
- 唱片曲目 (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:public class CD {
private String title;
private int year;
private Artist artist;
public String getTitle() {return title;}
public int getYear() {return year;}
public Artist getArtist() {return artist;}
public void setTitle(String t){title = t;}
public void setYear(int y){year = y;}
public void setArtist(Artist a){artist = a;}
}將"歌唱者姓名"作為可共用的ConcreteFlyweight:public class Artist {
//內部狀態
private String name;
// note that Artist is immutable.
String getName(){return name;}
Artist(String n){
name = n;
}
}再看看Flyweight factory,專門用來製造上面的可共用的ConcreteFlyweight:Artistpublic class ArtistFactory {
Hashtable pool = new Hashtable();
Artist getArtist(String key){
Artist result;
result = (Artist)pool.get(key);
////產生新的Artist
if(result == null) {
result = new Artist(key);
pool.put(key,result);
}
return result;
}
}當你有幾千張甚至更多CD時,Flyweight模式將節省更多空間,共用的flyweight越多,空間節省也就越大。
享元模式
概述
運用共用技術有效地支援大量細粒度的對象。
適用性
當都具備下列情況時,使用Flyweight模式: 1.一個應用程式使用了大量的對象。 2.完全由於使用大量的對象,造成很大的儲存開銷。 3.對象的大多數狀態都可變為外部狀態。 4.如果刪除對象的外部狀態,那麼可以用相對較少的共用對象取代很多組對象。 5.應用程式不依賴於對象標識。由於Flyweight對象可以被共用,對於概念上明顯有別的對象,標識測試將返回真值。
參與者
1.Flyweight 描述一個介面,通過這個介面flyweight可以接受並作用於外部狀態。 2.ConcreteFlyweight 實現Flyweight介面,並為內部狀態(如果有的話)增加儲存空間。 ConcreteFlyweight對象必須是可共用的。它所儲存的狀態必須是內部的;即,它必須獨立於ConcreteFlyweight對象的情境。 3.UnsharedConcreteFlyweight 並非所有的Flyweight子類都需要被共用。Flyweight介面使共用成為可能,但它並不強制共用。 在Flyweight對象結構的某些層次,UnsharedConcreteFlyweight對象通常將ConcreteFlyweight對象作為子節點。 4.FlyweightFactory 建立並管理flyweight對象。 確保合理地共用flyweight。當使用者請求一個flyweight時,FlyweightFactory對象提供一個已建立的執行個體或者建立一個(如果不存在的話)。
類圖
例子
Flyweight
public interface Flyweight { void action(int arg);}
ConcreteFlyweight
public class FlyweightImpl implements Flyweight { public void action(int arg) { // TODO Auto-generated method stub System.out.println("參數值: " + arg); }}
FlyweightFactory
public class FlyweightFactory { private static Map flyweights = new HashMap(); public FlyweightFactory(String arg) { flyweights.put(arg, new FlyweightImpl()); } public static Flyweight getFlyweight(String key) { if (flyweights.get(key) == null) { flyweights.put(key, new FlyweightImpl()); } return flyweights.get(key); } public static int getSize() { return flyweights.size(); }}
Test
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Flyweight fly1 = FlyweightFactory.getFlyweight("a"); fly1.action(1); Flyweight fly2 = FlyweightFactory.getFlyweight("a"); System.out.println(fly1 == fly2); Flyweight fly3 = FlyweightFactory.getFlyweight("b"); fly3.action(2); Flyweight fly4 = FlyweightFactory.getFlyweight("c"); fly4.action(3); Flyweight fly5 = FlyweightFactory.getFlyweight("d"); fly4.action(4); System.out.println(FlyweightFactory.getSize()); }}
result
參數值: 1true參數值: 2參數值: 3參數值: 44
Java共用模式/享元模式(Flyweight模式)