享元模式:通过池技术,对细粒度对象提供共享支持
优点:节省对象创建时间,减少内存开支,降低性能消耗
标准类图:
抽象享元:
public abstract class FlyWeight {
protected String externalAttribute;//external attribute
public FlyWeight(String externalAttribute) {
super();
this.externalAttribute = externalAttribute;
}
protected abstract void operate();
}
具体享元:
public class ConcreteFlyWeight extends FlyWeight {
private String name;// internal attribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ConcreteFlyWeight(String externalAttribute) {
super(externalAttribute);
}
@Override
protected void operate() {
System.out.println("do some thing");
}
}
享元工厂:
public class FlyWeightFactory {
private static Map<String, FlyWeight> pool = new HashMap<>();
public static FlyWeight getFlyWeight(String key){
if(pool.containsKey(key)){
return pool.get(key);
}else{
ConcreteFlyWeight flyWeight = new ConcreteFlyWeight(key);
pool.put(key, flyWeight);
return flyWeight;
}
}
}
场景类:
public class Client {
public static void main(String[] args) {
FlyWeight flyWeight1 = FlyWeightFactory.getFlyWeight("key1");
FlyWeight flyWeight2 = FlyWeightFactory.getFlyWeight("key1");
FlyWeight flyWeight3 = FlyWeightFactory.getFlyWeight("key2");
System.out.println(flyWeight1);
System.out.println(flyWeight2);
System.out.println(flyWeight3);
}
}