Flyweight定義:
避免大量擁有相同內容的小類的開銷(如耗費內存)
為什麼使用?
面向對象語言的原則就是一切都是對象
說白點
Flyweight模式是一個提高程序效率和性能的模式
如何使用?
我們先從Flyweight抽象接口開始:
public interface Flyweight
{
public void operation( ExtrinsicState state );
}
//用於本模式的抽象數據類型(自行設計)
public interface ExtrinsicState { }
下面是接口的具體實現(ConcreteFlyweight)
public class ConcreteFlyweight implements Flyweight {
private IntrinsicState state;
public void operation( ExtrinsicState state )
{
//具體操作
}
}
當然
public class UnsharedConcreteFlyweight implements Flyweight {
public void operation( ExtrinsicState state ) { }
}
Flyweight factory負責維護一個Flyweight池(存放內部狀態)
public class FlyweightFactory {
//Flyweight pool
private Hashtable flyweights = new Hashtable();
public Flyweight getFlyweight( Object key ) {
Flyweight flyweight = (Flyweight) flyweights
if( flyweight == null ) {
//產生新的ConcreteFlyweight
flyweight = new ConcreteFlyweight();
flyweights
}
return flyweight;
}
}
至此
FlyweightFactory factory = new FlyweightFactory();
Flyweight fly
Flyweight fly
從調用上看
Flyweight模式在XML等數據源中應用
我們上面已經提到
每個CD有三個字段:
其中
首先看看數據源XML文件的內容:
<?xml version=
<collection>
<cd>
<title>Another Green World</title>
<year>
<artist>Eno
</cd>
<cd>
<title>Greatest Hits</title>
<year>
<artist>Holiday
</cd>
<cd>
<title>Taking Tiger Mountain (by strategy)</title>
<year>
<artist>Eno
</cd>
</collection>
雖然上面舉例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;}
}
將
public class Artist {
//內部狀態
private String name;
// note that Artist is immutable
String getName(){return name;}
Artist(String n){
name = n;
}
}
再看看Flyweight factory
public class ArtistFactory {
Hashtable pool = new Hashtable();
Artist getArtist(String key){
Artist result;
result = (Artist)pool
////產生新的Artist
if(result == null) {
result = new Artist(key);
pool
}
return result;
}
}
當你有幾千張甚至更多CD時
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27463.html