享元模式的定义
*享元(Flyweight)模式: * 运用共享技术来有效地支持大量细粒度对象的复用,它通过共享已经存在的对象来大幅减少需要创建的对象的数量丶避免创建大量相似对象的开销,从而提高系统资源利用率
- 如线程池
特点
- *优点: *
- 相同的对象只保存一份,这降低了系统中对象的数量,从而降低了系统中细粒度对象给内存带来的压力
- *缺点: *
- 为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性
- 读取享元模式的外部状态会使得运行时间稍微变长
模式的结构与实现
模式的结构
抽象享元角色(Flyweight):是所有的具体享元类的基类,为具体享元规范需要实现的公共接口,非享元的外部状态以参数的形式通过方法传入
具体享元(Concrete Flyweight)角色:实现抽象享元角色中所规定的接口
非享元(Unsharable Flyweight)角色:是不可以共享的外部状态,它以参数的形式注入具体享元的相关方法中
享元工厂(Flyweight Factory)角色:负责创建和管理享元角色。当客户对象请求一个享元对象时,享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象
图中UnsharedConcreteFlyweight是非享元角色,里面包含了非共享的外部状态信息info,而Flyweight是抽象享元角色,里面包含了享元方法operation(UnsharedConcreteFlyweight state),非享元的外部状态以参数的形式传入
模式的实现**
/** * 享元模式: * 通俗的说: 就是对于相同的对象可以共享的方式使用,不需要频繁创建新对象, * 对于非共享内容可以通过参数方式传递给共享对象 */ //非享元角色 - 非共享的通过参数传递给具体享元角色 class UnsharedConcreteFlyweight{ private String info; public UnsharedConcreteFlyweight(String info) { this.info = info; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } } //抽象享元角色 interface Flyweight{ void operation(UnsharedConcreteFlyweight state); } //具体享元角色 class ConcreteFlyweight implements Flyweight{ private String key; public ConcreteFlyweight(String key) { this.key = key; System.out.println("具体享元"+key+"被创建!"); } @Override public void operation(UnsharedConcreteFlyweight state) { System.out.print("具体享元"+key+"被调用!"); System.out.println("非具体享元"+state.getInfo()); } } //享元工厂 class FlyweightFactory{ private HashMap<String,Flyweight> flyweights = new HashMap<>(); public Flyweight getFlyweight(String key){ Flyweight flyweight = flyweights.get(key); if(flyweight != null){ System.out.println("具体想元"+key+"已经存在,被成功获取!"); } else{ flyweight = new ConcreteFlyweight(key); flyweights.put(key,flyweight); } return flyweight; } } //客户端 public class FlyweightPattern { public static void main(String[] args) { FlyweightFactory factory=new FlyweightFactory(); Flyweight f01=factory.getFlyweight("a"); Flyweight f02=factory.getFlyweight("a"); Flyweight f03=factory.getFlyweight("a"); Flyweight f11=factory.getFlyweight("b"); Flyweight f12=factory.getFlyweight("b"); f01.operation(new UnsharedConcreteFlyweight("第1次调用a。")); f02.operation(new UnsharedConcreteFlyweight("第2次调用a。")); f03.operation(new UnsharedConcreteFlyweight("第3次调用a。")); f11.operation(new UnsharedConcreteFlyweight("第1次调用b。")); f12.operation(new UnsharedConcreteFlyweight("第2次调用b。")); } }