蝇量模式(享元模式)
享元模式(Flyweight Pattern)是一种结构型设计模式,旨在通过共享对象来最大化减少内存使用和对象创建的数量,以提高应用程序的性能。
在享元模式中,如果多个对象需要相同的信息,则将此信息提取出来并作为单个共享对象使用。所有需要此信息的对象都共享此共享对象,从而减少了内存使用和对象创建的数量。享元模式通常与工厂模式一起使用,以确保创建并返回现有对象。
下面是一个简单的享元模式示例:
// 享元接口
interface Flyweight {
void operation();
}
// 具体享元
class ConcreteFlyweight implements Flyweight {
private String sharedState;
public ConcreteFlyweight(String sharedState) {
this.sharedState = sharedState;
}
public void operation() {
System.out.println("ConcreteFlyweight: " + sharedState);
}
}
// 享元工厂
class FlyweightFactory {
private Map<String, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String sharedState) {
Flyweight flyweight = flyweights.get(sharedState);
if (flyweight == null) {
flyweight = new ConcreteFlyweight(sharedState);
flyweights.put(sharedState, flyweight);
}
return flyweight;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight flyweight1 = factory.getFlyweight("shared state");
flyweight1.operation();
Flyweight flyweight2 = factory.getFlyweight("shared state");
flyweight2.operation();
System.out.println(flyweight1 == flyweight2); // 输出 true
}
}
在上面的示例中,Flyweight 是享元接口,ConcreteFlyweight 是具体享元。FlyweightFactory 是享元工厂,负责创建并返回享元对象。客户端代码通过创建 FlyweightFactory 对象,然后使用它来获取享元对象。注意,当客户端请求一个共享状态的对象时,享元工厂会检查是否已经存在具有该状态的对象。如果对象不存在,则会创建一个新的对象并将其存储在内部缓存中。如果对象已经存在,则返回现有对象。