运用共享技术有效地支持大量细粒度的对象。
其中
- // Flyweight 接口
- interface Flyweight {
- void operation(ExtrinsicState state);
- }
-
- // ConcreteFlyweight 实现
- class ConcreteFlyweight implements Flyweight {
- private String intrinsicState;
-
- public ConcreteFlyweight(String intrinsicState) {
- this.intrinsicState = intrinsicState;
- }
-
- @Override
- public void operation(ExtrinsicState state) {
- System.out.println("Intrinsic state: " + intrinsicState);
- System.out.println("Extrinsic state: " + state.getValue());
- }
- }
-
- // 外部状态
- class ExtrinsicState {
- private String value;
-
- public ExtrinsicState(String value) {
- this.value = value;
- }
-
- public String getValue() {
- return value;
- }
- }
-
- // Flyweight 工厂
- class FlyweightFactory {
- private static Map
pool = new HashMap<>(); -
- public static Flyweight get(String intrinsicState) {
- if (!pool.containsKey(intrinsicState)) {
- pool.put(intrinsicState, new ConcreteFlyweight(intrinsicState));
- }
- return pool.get(intrinsicState);
- }
- }
-
- // 客户端
- class Client {
- public static void main(String[] args) {
- ExtrinsicState state1 = new ExtrinsicState("state1");
- ExtrinsicState state2 = new ExtrinsicState("state2");
-
- Flyweight flyweight1 = FlyweightFactory.get("intrinsic1");
- Flyweight flyweight2 = FlyweightFactory.get("intrinsic2");
-
- flyweight1.operation(state1);
- flyweight2.operation(state2);
-
- System.out.println("Flyweight pool size: " + FlyweightFactory.pool.size());
- }
- }
Flyweight
接口定义了 Flyweight 对象必须实现的操作。ConcreteFlyweight
类实现了 Flyweight
接口,并存储了内部状态。ExtrinsicState
类表示外部状态。FlyweightFactory
类创建和管理 Flyweight 对象。Client
类使用 Flyweight 对象并提供外部状态。