标签:
定义:使用享元对象可有效的支持大量的细粒度的对象
类图:
代码:
public abstract class Flyweight { private String intrinsic; protected final String extrinsic; public Flyweight(String extrinsic){ this.extrinsic = extrinsic; } public abstract void operator(); public String getInstrinsic(){ return intrinsic; } public void setInstrinsic(String instrinsic){ this.intrinsic = instrinsic; } }
public class ConcreteFlyweight1 extends Flyweight{ public ConcreteFlyweight(String extrinsic) { super(extrinsic); // TODO Auto-generated constructor stub } @Override public void operator() { // TODO Auto-generated method stub } }
public class ConcreteFlyweight2 extends Flyweight{ public ConcreteFlyweight(String extrinsic) { super(extrinsic); // TODO Auto-generated constructor stub } @Override public void operator() { // TODO Auto-generated method stub } }
public class FlyweightFactory { private static HashMap<String,Flyweight> pool = new HashMap<String,Flyweight>(); public static Flyweight getFlyweight(String extrinsic){ Flyweight flyweight = null; if(pool.containsKey(extrinsic)){ flyweight = pool.get(extrinsic); }else{ flyweight = new ConcreteFlyweight1(extrinsic); pool.put(extrinsic, flyweight); } return flyweight; } }
大大减少应用程序创建的对象
缺点:
线程安全
标签:
原文地址:http://blog.csdn.net/renpengddxx/article/details/52159509