享元模式

181 阅读2分钟

这是我参与8月更文挑战的第19天,活动详情查看:8月更文挑战

享元模式

运用共享技术来有效地支持大量细粒度对象的复用。它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。

结构

  1. 抽象享元角色(Flyweight) :是所有的具体享元类的基类,为具体享元规范需要实现的公共接口,非享元的外部状态以参数的形式通过方法传入。
  2. 具体享元(Concrete Flyweight)角色:实现抽象享元角色中所规定的接口的类称为享元对象。
  3. 非享元(Unsharable Flyweight)角色:是不可以共享的外部状态,它以参数的形式注入具体享元的相关方法中。当需要时可以直接实例化创建。
  4. 享元工厂(Flyweight Factory)角色:负责创建和管理享元角色。当客户对象请求一个享元对象时,享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。

演示

1、抽象享元角色

public abstract class Clothes {
    public abstract void info();
}

2、具体享元角色

public class ClothesType extends Clothes {
    private String name;
    public ClothesType(String name) {
        this.name = name;
    }
    @Override
    public void info() {
        System.out.println("衣服:" + this.name);
    }
}

3、享元工厂

public class ClothesFactory {
    private HashMap<String, ClothesType> map = new HashMap<>();
    public ClothesType getClothes(String name) {
        if (!map.containsKey(name)) {
            System.out.print("新共享数据:");
            map.put(name, new ClothesType(name));
        } else {
            System.out.print("数据已存在:");
        }
        return map.get(name);
    }
}

4、客户端

public class Client {
    public static void main(String[] args) {
        ClothesFactory factory = new ClothesFactory();
        ClothesType clothesType = factory.getClothes("上衣");
        clothesType.info(); // 新共享数据:衣服:上衣
        ClothesType clothesType2 = factory.getClothes("裤子");
        clothesType2.info(); // 新共享数据:衣服:裤子
        ClothesType clothesType3 = factory.getClothes("裤子");
        clothesType3.info(); // 数据已存在:衣服:裤子
    }
}

总结

从结果可以看出,当数据不存在时先创建再获取数据,存在时直接获取数据。

因此,这个模式的优点就是:相同对象只保存一份,降低了系统中对象的数量,从而降低了对象给内存带来的压力;

缺点也很明显:提高了系统的复杂度,需要分离出外部状态和内部状态