享元模式(Flyweight),运用共享技术有效地支持大量细粒度的对象。[DP]
解决对象的开销问题,像围棋,一盘棋理论上有361个空位可以放棋子,那如果用常规的面向对象方式编程,每盘棋都可能有两三百个棋子对象产生,一台服务器就很难支持更多的玩家玩围棋游戏了,毕竟内存空间还是有限的。如果用了享元模式来处理棋子,那么棋子对象可以减少到只有两个实例。
import java.util.HashMap;
import java.util.Map;
// 享元接口
interface Flyweight {
void operation(String extrinsicState);
}
// 具体享元类
class ConcreteFlyweight implements Flyweight {
private String intrinsicState;
public ConcreteFlyweight(String state) {
this.intrinsicState = state;
}
@Override
public void operation(String extrinsicState) {
System.out.println("Intrinsic state: " + intrinsicState + ", Extrinsic state: " + extrinsicState);
}
}
// 享元工厂类
class FlyweightFactory {
private Map<String, Flyweight> flyweightPool = new HashMap<>();
public Flyweight getFlyweight(String state) {
Flyweight flyweight = flyweightPool.get(state);
if (flyweight == null) {
flyweight = new ConcreteFlyweight(state);
flyweightPool.put(state, flyweight);
}
return flyweight;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight1 = factory.getFlyweight("state1");
Flyweight flyweight2 = factory.getFlyweight("state2");
Flyweight flyweight3 = factory.getFlyweight("state1");
flyweight1.operation("extrinsicStateA");
flyweight2.operation("extrinsicStateB");
flyweight3.operation("extrinsicStateA");
// 输出将显示flyweight1和flyweight3是同一个对象,因为它们共享相同的内在状态"state1"
}
}