在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
在這個例子中,享元工廠類根據傳入的參數來獲取共享對象。如果共享對象已經創建過,則直接返回;如果沒有創建過,則創建一個新的共享對象,并將其保存在集合中。客戶端通過享元工廠來獲取共享對象,并調用其操作方法。由于共享對象是可共享的,所以多個客戶端可以共享同一個對象,減少了內存的使用。