- 享元角色抽象类
public abstract class AbstractFlyweight {
//外部状态
private final String extrinsic;
//内部状态
private String intrinsic;
public AbstractFlyweight(String extrinsic) {
this.extrinsic = extrinsic;
}
public String getIntrinsic() {
return intrinsic;
}
public void setIntrinsic(String intrinsic) {
this.intrinsic = intrinsic;
}
//公共方法
protected abstract void operate();
}
- 享元角色抽象类实现类
public class ConcreteFlyweight extends AbstractFlyweight {
public ConcreteFlyweight(String extrinsic) {
super(extrinsic);
}
@Override
protected void operate() {
//具体逻辑
}
}
- 享元角色工厂类
public class FlyweightFactory {
//享元池
private static Map<String, AbstractFlyweight> pool = new HashMap<>();
//获取享元角色
public static AbstractFlyweight getFlyweight(String extrinsic) {
AbstractFlyweight flyweight;
if (pool.containsKey(extrinsic)) {
flyweight = pool.get(extrinsic);
} else {
flyweight = new ConcreteFlyweight(extrinsic);
pool.put(extrinsic, flyweight);
}
return flyweight;
}
}
- 场景使用
AbstractFlyweight flyweight = FlyweightFactory.getFlyweight("key");
flyweight.operate();