享元模式java实例
时间: 2024-06-12 13:10:52 浏览: 72
好的,下面是享元模式的一个简单的 Java 实例:
```java
import java.util.HashMap;
public class FlyweightFactory {
private static final HashMap<String, Flyweight> flyweights = new HashMap<>();
public static Flyweight getFlyweight(String key) {
Flyweight flyweight = flyweights.get(key);
if (flyweight == null) {
flyweight = new ConcreteFlyweight();
flyweights.put(key, flyweight);
}
return flyweight;
}
}
public interface Flyweight {
void operation();
}
public class ConcreteFlyweight implements Flyweight {
@Override
public void operation() {
System.out.println("ConcreteFlyweight operation");
}
}
public class Client {
public static void main(String[] args) {
Flyweight flyweight1 = FlyweightFactory.getFlyweight("key1");
Flyweight flyweight2 = FlyweightFactory.getFlyweight("key1");
flyweight1.operation();
flyweight2.operation();
System.out.println(flyweight1 == flyweight2);
}
}
```
在这个例子中,`FlyweightFactory` 是享元工厂类,用于创建和管理享元对象。`Flyweight` 是享元接口,定义了享元对象的操作。`ConcreteFlyweight` 是具体的享元实现类,实现了 `Flyweight` 接口。`Client` 是客户端类,用于测试享元模式。
在 `Client` 类中,我们通过 `FlyweightFactory.getFlyweight()` 方法获取享元对象,并调用其 `operation()` 方法执行操作。由于我们获取的是同一个 key 对应的享元对象,因此它们的引用相同,输出结果为 `true`。
阅读全文