Flyweight

享元模式:运用共享技术有效地支持大量细粒度的对象。

享元模式可以避免大量相似类的开销,在程序设计中,有时需要生成大量细粒度的类实例来表示数据。如果能发现这些类实例除了几个参数外基本相同,有时就能够大幅度减少需要实例化的类的数量。如果能把那些参数移动到类实例的外面,有方法调用时将它们传递进来,就可以通过共享大幅度减少单个实例的数目。

如果一个应用程序使用大量的对象,而大量的对象造成了很多的存储开销时就应该考虑;还有就是对象的大多数状态可以外部状态,如果删除了对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑享元模式。

Flyweight:它是所有具体共享的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。

ConcreteFlyweight:继承Flyweight,并为内部状态增加存储空间。

UnsharedConcreteFlyweight:不需要共享的Flyweight子类。因为Flyweight接口共享成为可能,但它并不强制共享。

FlyweightFactory:一个享元工厂,用来创建并管理Flyweight对象。它主要用来确保合理共享Flyweight。当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的Flyweight对象或新创建一个。(如果不存在)

abstract class Flyweight {

    protected String name;

    public Flyweight(String name) {
        this.name = name;
    }

    public abstract void operation();

}
class ConcreteFlyweight extends Flyweight {

    public ConcreteFlyweight(String name) {
        super(name);
    }

    @Override
    public void operation() {
        System.out.println("ConcreteFlyweight - " + name);
    }

}
class UnshareConcreteFlyweight extends Flyweight {

    public UnshareConcreteFlyweight(String name) {
        super(name);
    }

    @Override
    public void operation() {
        System.out.println("UnshareConcreteFlyweight - " + name);
    }

}
class FlyweightFactory {

    private HashMap<String, Flyweight> flyweights = new HashMap<String, Flyweight>();

    public FlyweightFactory() {
        flyweights.put("A", new ConcreteFlyweight("A"));
        flyweights.put("B", new ConcreteFlyweight("B"));
    }

    public Flyweight getFlyweight(String key) {
        if ("X".equals(key)) {
            return new UnshareConcreteFlyweight("X");
        }
        if (!flyweights.containsKey(key)) {
            flyweights.put(key, new ConcreteFlyweight(key));
        }
        return flyweights.get(key);
    }

    public int getCount() {
        return flyweights.size();
    }

}
    public static void main(String[] args) {

        FlyweightFactory factory = new FlyweightFactory();

        Flyweight f = factory.getFlyweight("A");
        f.operation();

        f = factory.getFlyweight("Z");
        f.operation();

        System.out.println(factory.getCount());

    }

打印结果:
ConcreteFlyweight - A
ConcreteFlyweight - Z
3

原文地址:https://www.cnblogs.com/xuekyo/p/2618011.html