设计模式(十一)———享元模式(Flyweigth Pattern):共享对象,避免浪费

设计模式(十一)———享元模式(Flyweigth Pattern):共享对象,避免浪费

Scroll Down

Intent

运用共享技术有效地支持大量细粒度的对象

应用实例

  • 系统有大量相似对象
  • 需要缓冲池的场景

使用场景

  • 系统有大量相似对象
  • 需要缓冲池的场景

优点

  • 大大减少对象的创建,降低系统的内存,使效率提高

缺点

  • 提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱

Class Diagram

image.png

Flyweight(轻量级)

按照通常方式编写程序会导致程序变重,所以如果能够共享实例会比较好,而Flyweight角色表示的就是那些实例会被共享的类

ConcreteFlyweight(真实的轻量级)

  • IntrinsicState:内部状态,享元对象共享内部状态
  • ExtrinsicState:外部状态,每个享元对象的外部状态不同

Flyweight(轻量级工厂)

FlyweightFactory角色是生成Flyweight角色的工厂。在工厂中生成Flyweight角色可以实现共享实例

Client(请求者)

Client角色负责调用FlyweightFactory角色来生成Flyweigth角色

Implementation

观看电影需要操作很多电器,使用外观模式实现一键看电影功能

public interface Flyweight {
    void doOperation(String extrinsicState);
}
public class ConcreteFlyweight implements Flyweight {

    private String intrinsicState;

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

    @Override
    public void doOperation(String extrinsicState) {
        System.out.println("Object address: " + System.identityHashCode(this));
        System.out.println("IntrinsicState: " + intrinsicState);
        System.out.println("ExtrinsicState: " + extrinsicState);
    }
}
public class FlyweightFactory {

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

    Flyweight getFlyweight(String intrinsicState) {
        if (!flyweights.containsKey(intrinsicState)) {
            Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
            flyweights.put(intrinsicState, flyweight);
        }
        return flyweights.get(intrinsicState);
    }
}
public class Client {

    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight flyweight1 = factory.getFlyweight("aa");
        Flyweight flyweight2 = factory.getFlyweight("aa");
        flyweight1.doOperation("x");
        flyweight2.doOperation("y");
    }
}

输出结果

Object address: 1163157884
IntrinsicState: aa
ExtrinsicState: x
Object address: 1163157884
IntrinsicState: aa
ExtrinsicState: y