UML
所有具体享元类的超类或接口
public abstract class FlyWeight {
public abstract void operation(int extrinsicstate);
}
具体的FlyWeight
public class ConcreteFlyWeight extends FlyWeight {
@Override
public void operation(int extrinsicstate) {
System.out.println("具体的FlyWeight--->" + extrinsicstate);
}
}
不共享的具体的FlyWeight
public class UnsharedFlyWeight extends FlyWeight {
@Override
public void operation(int extrinsicstate) {
System.out.println("不共享的具体的FlyWeight--->" + extrinsicstate);
}
}
享元工厂 创建并管理FlyWeight对象
import java.util.Hashtable;
public class FlyWeightFactory {
private Hashtable<String, FlyWeight> hashtable = new Hashtable<>();
public FlyWeight getFlyWeight(String key) {
if (hashtable.containsKey(key)) {
return hashtable.get(key);
} else {
ConcreteFlyWeight concreteFlyWeight = new ConcreteFlyWeight();
hashtable.put(key, concreteFlyWeight);
return concreteFlyWeight;
}
}
public int getCount() {
return hashtable.size();
}
}
测试类
public class Main {
public static void main(String[] args) {
int extrinsicstate = 10;
FlyWeightFactory factory = new FlyWeightFactory();
FlyWeight f1 = factory.getFlyWeight("X");
f1.operation(--extrinsicstate);
FlyWeight f2 = factory.getFlyWeight("Y");
f2.operation(--extrinsicstate);
FlyWeight f3 = factory.getFlyWeight("Z");
f3.operation(--extrinsicstate);
FlyWeight f31 = factory.getFlyWeight("Z");
f31.operation(--extrinsicstate);
FlyWeight f32 = factory.getFlyWeight("Z");
f32.operation(--extrinsicstate);
FlyWeight f33 = factory.getFlyWeight("Z");
f33.operation(--extrinsicstate);
FlyWeight f4 = new UnsharedFlyWeight();
f4.operation(--extrinsicstate);
System.out.println("享元数量--->" + factory.getCount());
}
}
运行结果