阅读量:0
在Java中,享元模式可以通过以下步骤来实现:
- 定义共享对象的接口(享元接口):这个接口定义了共享对象的操作方法。
public interface Flyweight { void operation(); }
- 实现共享对象的具体类(具体享元类):这些类实现了享元接口,并实现了共享对象的操作方法。
public class ConcreteFlyweight implements Flyweight { private String intrinsicState; public ConcreteFlyweight(String intrinsicState) { this.intrinsicState = intrinsicState; } @Override public void operation() { System.out.println("具体享元对象的操作:" + intrinsicState); } }
- 创建享元工厂类:这个工厂类负责创建和管理共享对象,通过一个集合来保存已经创建的共享对象。
public 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; } } }
- 使用享元对象:在客户端中通过享元工厂来获取共享对象,并调用其操作方法。
public class Client { public static void main(String[] args) { FlyweightFactory factory = new FlyweightFactory(); Flyweight flyweight1 = factory.getFlyweight("A"); flyweight1.operation(); Flyweight flyweight2 = factory.getFlyweight("B"); flyweight2.operation(); Flyweight flyweight3 = factory.getFlyweight("A"); flyweight3.operation(); } }
输出结果:
具体享元对象的操作:A 具体享元对象的操作:B 具体享元对象的操作:A
在这个例子中,享元工厂类根据传入的参数来获取共享对象。如果共享对象已经创建过,则直接返回;如果没有创建过,则创建一个新的共享对象,并将其保存在集合中。客户端通过享元工厂来获取共享对象,并调用其操作方法。由于共享对象是可共享的,所以多个客户端可以共享同一个对象,减少了内存的使用。