GOF:運(yùn)用共享技術(shù)有效地支持大量細(xì)粒度的對(duì)象。
解釋一下概念:也就是說在一個(gè)系統(tǒng)中如果有多個(gè)相同的對(duì)象,那么只共享一份就可以了,不必每個(gè)都去實(shí)例化一個(gè)對(duì)象。比如說(這里引用GOF書中的例子)一個(gè)文本系統(tǒng),每個(gè)字母定一個(gè)對(duì)象,那么大小寫字母一共就是52個(gè),那么就要定義 52個(gè)對(duì)象。如果有一個(gè)1M的文本,那么字母是何其的多,如果每個(gè)字母都定義一個(gè)對(duì)象那么內(nèi)存早就爆了。那么如果要是每個(gè)字母都共享一個(gè)對(duì)象,那么就大大節(jié)約了資源。
在Flyweight模式中,由于要產(chǎn)生各種各樣的對(duì)象,所以在Flyweight(享元)模式中常出現(xiàn)Factory 模式。Flyweight的內(nèi)部狀態(tài)是用來共享的,F(xiàn)lyweight factory負(fù)責(zé)維護(hù)一個(gè)對(duì)象存儲(chǔ)池(Flyweight Pool)來存放內(nèi)部狀態(tài)的對(duì)象。Flyweight模式是一個(gè)提高程序效率和性能的模式,會(huì)大大加快程序的運(yùn)行速度。應(yīng)用場合很多,下面舉個(gè)例子:
package Flyweight;
public abstract class Flyweight
...
{
public abstract void operation();
}//end abstract class Flyweight
在實(shí)現(xiàn)一個(gè)具體類:
package Flyweight;
public class ConcreteFlyweight extends Flyweight
...
{
private String string;
public ConcreteFlyweight(String str)
...
{
string = str;
}//end ConcreteFlyweight(...)
public void operation()
...
{
System.out.println("Concrete---Flyweight : " + string);
}//end operation()
}//end class ConcreteFlyweight
實(shí)現(xiàn)一個(gè)工廠方法類:
package Flyweight;
import java.util.Hashtable;
public class FlyweightFactory
...
{
private Hashtable flyweights = new Hashtable();//--------1
public FlyweightFactory() ...{}
public Flyweight getFlyWeight(Object obj)
...
{
Flyweight flyweight = (Flyweight) flyweights.get(obj);//-------2
if(flyweight == null) ...{//-----------------------------------3
//產(chǎn)生新的ConcreteFlyweight
flyweight = new ConcreteFlyweight((String)obj);
flyweights.put(obj, flyweight);//------------------------------5
}
return flyweight;//--------------------------------------------6
}//end GetFlyWeight(...)
public int getFlyweightSize()
...
{
return flyweights.size();
}
}//end class FlyweightFactory
北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |