一、UML类图
二、代码示例
public class Client {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight = factory.getFlyweight("name");
}
}
public class FlyweightFactory {
private Map<String, Flyweight> pool = new HashMap<>();
public Flyweight getFlyweight(String name) {
Flyweight flyweight = pool.get(name);
if (flyweight == null) {
flyweight = new ConcreteFlyweight();
pool.put(name, flyweight);
}
return flyweight;
}
}
public interface Flyweight {
void operation();
}
public class ConcreteFlyweight implements Flyweight{
@Override
public void operation() { }
}
三、角色介绍
- Client(客户端):
客户端角色,程序的调用者。 - FlyweightFactory(轻量级工厂):
该角色负责生成Flyweight角色。 - Flyweight(轻量级):
该角色表示会被共享的抽象角色。 - ConcreteFlyweight(具体轻量级):
该角色表示会被共享的具体角色。
|