享元模式:运用共享技术有效地支持大量细粒度的对象
如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用;还有对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象。
UML:
JAVA:
public class FlyWeightTest {
public static void main(String[] args) {
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.getFlyweight("X");
fx.operation(--extrinsicstate);
Flyweight fy = f.getFlyweight("Y");
fx.operation(--extrinsicstate);
UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight();
uf.operation(--extrinsicstate);
}
}
class FlyweightFactory{
private Hashtable flyweights = new Hashtable();
public FlyweightFactory(){
flyweights.put("X",new ConcreteFlyweight());
flyweights.put("Y",new ConcreteFlyweight());
flyweights.put("Z",new ConcreteFlyweight());
}
public Flyweight getFlyweight(String key){
return (Flyweight) flyweights.get(key);
}
}
abstract class Flyweight{
public abstract void operation(int extrinsicstate);
}
class ConcreteFlyweight extends Flyweight{
@Override
public void operation(int extrinsicstate) {
System.out.println("具体实现Flyweight:"+extrinsicstate);
}
}
//不需要共享的子类
class UnsharedConcreteFlyweight extends Flyweight{
@Override
public void operation(int extrinsicstate) {
System.out.println("不共享的 具体实现Flyweight:"+extrinsicstate);
}
}