flyweightは日本語で「フライ級」という意味になる.Flyweightパターンは,同様のオブジェクトを別々の箇所で使用する際に,一つのオブジェクトを再利用することで,メモリ消費量を削減するパターン.
Flyweightパターンの主な要素は以下である.
javaimport java.util.HashMap;
import java.util.Map;
// Flyweight
interface Flyweight {
void operation(int extrinsicState);
}
// Concrete Flyweight
class ConcreteFlyweight implements Flyweight {
private String intrinsicState;
public ConcreteFlyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
@Override
public void operation(int extrinsicState) {
System.out.println("ConcreteFlyweight operation: (Extrinsic State: " + extrinsicState + ", Intrinsic State: " + intrinsicState + ")");
}
}
// Flyweight Factory
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;
}
}
}
// Client
public class FlyweightPattern {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight1 = factory.getFlyweight("key1");
Flyweight flyweight2 = factory.getFlyweight("key2");
Flyweight flyweight3 = factory.getFlyweight("key1");
flyweight1.operation(1);
flyweight2.operation(2);
flyweight3.operation(3);
}
}
Singletonみたい.
Singletonは1つのインスタンスを保持・再利用するのに対し,Flyweightはキーと値を一対一で保存する.