1 简介
享元模式(Flyweight Pattern)定义:运用共享技术有效地支持大量细粒度对象的复用。系统只是用少量的对象而这些对象都很相似,状态变化很小,可以实现对象的多次复用。
2 代码
(1)抽象享元类(Flyweight)
public interface Flyweight {
public void operation(String extrinsicState);
}
(2)具体享元类(ConcreteFlyweight)
public class ConcreteFlyweight implements Flyweight{
private String instrinsicState;
@Override
public void operation(String extrinsicState) {
}
}
(3)非共享具体享元类(UnsharedConcreteFlyweight)
public class UnsharedConcreteFlyweight implements Flyweight{
private String allState;
@Override
public void operation(String extrinsicState) {
}
}
(4)享元工厂(FlyweightFactory)
import java.util.HashMap;
public class FlyweightFactory {
private HashMap<String,Flyweight> flyweights=new HashMap<String,Flyweight>();
public Flyweight getFlyweight(String key) {
if(flyweights.containsKey(key)) {
return flyweights.get(key);
}else {
Flyweight fw=new ConcreteFlyweight();
flyweights.put(key, fw);
return fw;
}
}
}