金三银四面试题(二十四):享元模式知多少?
import java.util.HashMap;
import java.util.Map;
// 享元接口
interface Flyweight {
void operation(String externalState);
}
// 具体享元类
class ConcreteFlyweight implements Flyweight {
private final String intrinsicState;
public ConcreteFlyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
@Override
public void operation(String externalState) {
System.out.println("Intrinsic state: " + intrinsicState + ", External state: " + externalState);
}
}
// 享元工厂
class FlyweightFactory {
private final Map<String, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String key) {
Flyweight flyweight = flyweights.get(key);
if (flyweight == null) {
flyweight = new ConcreteFlyweight(key);
flyweights.put(key, flyweight);
}
return flyweight;
}
public int getFlyweightCount() {
return flyweights.size();
}
}
// 客户端代码
public class FlyweightPatternDemo {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
// 获取享元对象并执行操作
Flyweight flyweight1 = factory.getFlyweight("State1");
flyweight1.operation("External1");
Flyweight flyweight2 = factory.getFlyweight("State1");
flyweight2.operation("External2");
Flyweight flyweight3 = factory.getFlyweight("State2");
flyweight3.operation("External1");
// 显示享元对象的数量
System.out.println("Number of flyweight objects: " + factory.getFlyweightCount());
}
}