享元模式(Flyweight):運用共享的技術有效地支持大量細粒度的對象。主要目的是實現對象的共享,即共享池,當系統中對象多的時候可以減少內存的開銷。在某種程度上,你可以把單例看成是享元的一種特例。
##一、uml建模:

##二、代碼實現
~~~
/**
* 享元模式(Flyweight):運用共享的技術有效地支持大量細粒度的對象。
*
* 主要目的是實現對象的共享,即共享池,當系統中對象多的時候可以減少內存的開銷。
*/
abstract class FlyWeight {
public abstract void method();
}
/**
* 創建持有key的子類
*/
class SubFlyWeight extends FlyWeight {
private String key;
public SubFlyWeight(String key) {
this.key = key;
}
@Override
public void method() {
System.out.println("this is the sub method,and the key is " + this.key);
}
}
/**
* 享元工廠:負責創建和管理享元對象
*/
class FlyweightFactory {
private Map<String, FlyWeight> map = new HashMap<String, FlyWeight>();
/**
* 獲取享元對象
*/
public FlyWeight getFlyWeight(String key) {
FlyWeight flyWeight = map.get(key);
if (flyWeight == null) {
flyWeight = new SubFlyWeight(key);
map.put(key, flyWeight);
}
return flyWeight;
}
/**
* 獲取享元對象數量
*/
public int getCount() {
return map.size();
}
}
/**
* 客戶端測試類
*
* @author Leo
*/
public class Test {
public static void main(String[] args) {
/**
* 創建享元工廠
*/
FlyweightFactory factory = new FlyweightFactory();
/***第一種情況:key相同時 *********/
FlyWeight flyWeightA = factory.getFlyWeight("aaa");
FlyWeight flyWeightB = factory.getFlyWeight("aaa");
/**
* 透過打印結果為true可以知道: 由于key都為"aaa",所以flyWeightA和flyWeightB指向同一塊內存地址
*/
System.out.println(flyWeightA == flyWeightB);
flyWeightA.method();
flyWeightB.method();
/**
* 享元對象數量:1
*/
System.out.println(factory.getCount());
/***第二種情況:key不相同時 *********/
System.out.println("\n======================================");
FlyWeight flyWeightC = factory.getFlyWeight("ccc");
/**
* 打印結果為false
*/
System.out.println(flyWeightA == flyWeightC);
flyWeightC.method();
/**
* 享元對象數量:2
*/
System.out.println(factory.getCount());
}
}
~~~
打印結果:
~~~
true
this is the sub method,and the key is aaa
this is the sub method,and the key is aaa
1
======================================
false
this is the sub method,and the key is ccc
2
~~~
##三、總結
享元與單例的區別:1、與單例模式不同,享元模式是一個類可以有很多對象(共享一組對象集合),而單例是一個類僅一個對象;2、它們的目的也不一樣,享元模式是為了節約內存空間,提升程序性能(避免大量的new操作),而單例模式則主要是共享單個對象的狀態及特征。
- 前言
- (一)策略模式建模與實現
- (二)觀察者模式建模與實現
- (三)裝飾者模式建模與實現
- (四)工廠方法模式建模與實現
- (五)抽象工廠模式建模與實現
- (六)單例模式建模與實現
- (七)命令模式建模與實現
- (八)適配器模式建模與實現
- (九)外觀模式建模與實現
- (十)模板方法模式建模與實現
- (十一)迭代器模式建模與實現
- (十二)組合模式建模與實現
- (十三)狀態模式建模與實現
- (十四)代理模式建模與實現
- (十五)建造者模式建模與實現
- (十六)原型模式建模與實現
- (十七)橋接模式建模與實現
- (十八)責任鏈模式建模與實現
- (十九)備忘錄模式建模與實現
- (二十)解釋器模式建模與實現
- (二十一)享元模式建模與實現
- (二十二)中介者模式建模與實現
- (二十三)訪問者模式建模與實現
- Java設計模式博客全目錄