内容纲要
享元模式(Flyweight Pattern)是一种结构型设计模式,它通过共享已经存在的对象,减少系统中对象的数量,以降低内存占用和计算开销。享元模式主要用于处理大量相似对象的情况,它可以有效地减小内存消耗,提高性能。
以下是一个简单的Java实现:
- 创建享元接口(Flyweight Interface),表示享元对象的接口:
public interface Flyweight {
void operation(String externalState);
}
- 创建具体享元类(Concrete Flyweight),实现享元接口:
public class ConcreteFlyweight implements Flyweight {
private String internalState;
public ConcreteFlyweight(String internalState) {
this.internalState = internalState;
}
@Override
public void operation(String externalState) {
System.out.println("Internal State: " + internalState + ", External State: " + externalState);
}
}
- 创建享元工厂类(Flyweight Factory),用于创建和管理享元对象:
import java.util.HashMap;
import java.util.Map;
public class FlyweightFactory {
private Map<String, Flyweight> flyweights;
public FlyweightFactory() {
flyweights = new HashMap<>();
}
public Flyweight getFlyweight(String key) {
if (!flyweights.containsKey(key)) {
flyweights.put(key, new ConcreteFlyweight(key));
}
return flyweights.get(key);
}
}
- 使用享元模式创建对象:
public class Main {
public static void main(String[] args) {
FlyweightFactory flyweightFactory = new FlyweightFactory();
Flyweight flyweight1 = flyweightFactory.getFlyweight("A");
flyweight1.operation("Red");
Flyweight flyweight2 = flyweightFactory.getFlyweight("B");
flyweight2.operation("Blue");
Flyweight flyweight3 = flyweightFactory.getFlyweight("A");
flyweight3.operation("Green");
System.out.println("flyweight1 == flyweight3: " + (flyweight1 == flyweight3));
}
}
运行上述代码,你将看到:
Internal State: A, External State: Red
Internal State: B, External State: Blue
Internal State: A, External State: Green
flyweight1 == flyweight3: true
享元模式通过共享已经存在的对象,减少系统中对象的数量,以降低内存占用和计算开销。这种模式在处理大量相似对象的情况时非常有用,它可以有效地减小内存消耗,提高性能。