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应该共享一个对象在实际的对象数中我们可以看出实际的对象却是只有个 |