享元模式的特点:
享元模式可以共享相同的对象,避免创建过多的对象实例,从而节省内存资源
使用场景:
常用于需要创建大量相似的对象的情况
享元接口类
public interface Flyweight { void operate(String extrinsicState); }
享元实现类
public class ConcreteFlyweight implements Flyweight {
@Override
public void operate(String extrinsicState) {
System.out.println("固有状态: " + intrinsicState);
System.out.println("外部状态 " + extrinsicState);
}
}
享元工厂类
public class FlyweightFactory {
private Map<String, Flyweight> flyweights;
public Flyweight getFlyweight(String intrinsicState) {
if (flyweights.containsKey(intrinsicState)) {
return flyweights.get(intrinsicState);
} else {
Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
flyweights.put(intrinsicState, flyweight);
return flyweight;
}
}
}
演示类
public class Demo {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
//保存固有状态
Flyweight flyweight1 = factory.getFlyweight("SharedState");
Flyweight flyweight2 = factory.getFlyweight("SharedState");
//处理外部状态
flyweight1.operate("ExtrinsicState1");
flyweight2.operate("ExtrinsicState2");
}
}
演示结果
为了使演示代码更简洁,我移除了构造方法和set/get方法