享元模式的定义: 使用共享对象可以有效的支持大量的明细粒度的对象
享元模式是以共享的方式高效的支持大量的细粒度的对象,而享元模式能做到共享的关键是区分内部状态和外部状态。
享元模式的参与角色
抽象享元角色
public abstract class Flyweight {
private String innerState;
protected final String extrernalState;
public Flyweight(String externalState) {
this.extrernalState = externalState;
}
public abstract void operation();
public String getInnerState() {
return this.getInnerState();
}
public void setInnerState(String innerState) {
this.innerState = innerState;
}
}
具体享元角色
public class ConcreteFlyweight extends Flyweight{
public ConcreteFlyweight(String externalState) {
super(externalState);
// TODO Auto-generated constructor stub
}
@Override
public void operation() {
// TODO Auto-generated method stub
}
}
享元工厂
public class FlyweightFactory {
private static HashMap<String,Flyweight> pool = new HashMap();
public static Flyweight getFlyweight(String external) {
Flyweight fly = null;
if(pool.containsKey(external)) {
fly = pool.get(external);
}else {
fly = new ConcreteFlyweight(external);
pool.putIfAbsent(external, fly);
}
return fly;
}
}
享元模式的优点:
享元模式的使用场景