在Java中,享元模式可以通过以下步骤来实现:
public interface Flyweight {
void operation();
}
public class ConcreteFlyweight implements Flyweight {
private String intrinsicState;
public ConcreteFlyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
@Override
public void operation() {
System.out.println("具体享元对象的操作:" + intrinsicState);
}
}
public class FlyweightFactory {
private Map<String, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String key) {
if (flyweights.containsKey(key)) {
return flyweights.get(key);
} else {
Flyweight flyweight = new ConcreteFlyweight(key);
flyweights.put(key, flyweight);
return flyweight;
}
}
}
public class Client {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight1 = factory.getFlyweight("A");
flyweight1.operation();
Flyweight flyweight2 = factory.getFlyweight("B");
flyweight2.operation();
Flyweight flyweight3 = factory.getFlyweight("A");
flyweight3.operation();
}
}
输出结果:
具体享元对象的操作:A
具体享元对象的操作:B
具体享元对象的操作:A
在这个例子中,享元工厂类根据传入的参数来获取共享对象。如果共享对象已经创建过,则直接返回;如果没有创建过,则创建一个新的共享对象,并将其保存在集合中。客户端通过享元工厂来获取共享对象,并调用其操作方法。由于共享对象是可共享的,所以多个客户端可以共享同一个对象,减少了内存的使用。