java享元模式

在Java中实现享元模式,可以通过创建一个享元工厂(FlyweightFactory)和享元对象(Flyweight)来完成。享元模式用于共享可复用对象,以节省内存和提高性能。

下面是一个简单的示例:

首先,我们创建一个享元接口(Flyweight):

public interface Flyweight {
    void operation();
}
然后,我们创建具体享元类(ConcreteFlyweight),实现享元接口,并在其中实现具体的操作:

public class ConcreteFlyweight implements Flyweight {
    private String intrinsicState;

    public ConcreteFlyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    @Override
    public void operation() {
        System.out.println("具体享元对象,内部状态为:" + intrinsicState);
    }
}
接下来,我们创建享元工厂类(FlyweightFactory),用于创建和管理享元对象。在享元工厂中,我们使用一个 Map 来存储已经创建的享元对象,确保相同内部状态的享元对象只被创建一次:

import java.util.HashMap;
import java.util.Map;

public class FlyweightFactory {
    private Map flyweights;

    public FlyweightFactory() {
        flyweights = new HashMap<>();
    }

    public Flyweight getFlyweight(String intrinsicState) {
        if (!flyweights.containsKey(intrinsicState)) {
            Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
            flyweights.put(intrinsicState, flyweight);
        }
        return flyweights.get(intrinsicState);
    }
}
现在,我们可以使用享元模式来共享享元对象。首先,创建一个享元工厂对象,并使用享元工厂获取享元对象。由于相同内部状态的享元对象只会被创建一次,所以多个客户端使用相同内部状态的享元对象将共享同一个对象:

public class Main {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();

        Flyweight flyweight1 = factory.getFlyweight("state1");
        flyweight1.operation();

        Flyweight flyweight2 = factory.getFlyweight("state2");
        flyweight2.operation();

        Flyweight flyweight3 = factory.getFlyweight("state1");
        flyweight3.operation();
    }
}
输出结果:

具体享元对象,内部状态为:state1
具体享元对象,内部状态为:state2
具体享元对象,内部状态为:state1


这个例子展示了享元模式的实现方式。通过创建享元接口、具体享元类和享元工厂,可以实现共享享元对象,节省内存和提高性能,尤其在存在大量相似对象时,享元模式能够显著减少对象的数量。

你可能感兴趣的:(享元模式)