享元模式例子

享元模式,亦称cache、flyweight
内在状态:对象的常量数据,其他对象只能读不能改
外在状态:能“从外部”改变

享元模式将部分或全部内在状态抽取出来,单独存放一个地方(共享),以减少内存的占用,适合需要创建大量相似对象(只保留内在状态对象的引用)的场景。

伪代码例子:

// 内在状态类,享元类
class Flyweight is
    field repeatingState

    // 可能需要根据外在状态进行操作
    method operation(uniqueState) is
        // 执行操作...

// 需要创建大量相似对象的情景类,包含内在状态和外在状态
class Context is
    field uniqueState
    // 只保留享元类对象引用
    filed flyweight: Flyweight

    constructor Context(repeatingState, uniqueState) is
        this.uniqueState = uniqueState
        this.flyweight = FlyweightFactory.getFlyweight(repeatingState)

    method operation() is
        // xxx...
        flyweight.operation(uniqueState)

// 由工厂类根据repeatingState参数返回对应的享元类对象
class FlyweightFactory is
    // 缓存已经创建的享元类对象
    static field cache: Flyweight[]

    // 根据repeatingState参数返回对应的享元类对象
    static method getFlyweight(repeatingState): Flyweight is
        flyweight = cache.get(repeatingState)
        if (flyweight == null)
            flyweight = new Flyweight(repeatingState)
            chache.put(repeatingState, flyweight)
        return flyweight

// Client在构造情景类时传入repeatingState和uniqueState参数
class Demo is
    method example() is
        context = new Context(repeatingState, uniqueState)
        context.operation()

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