享元模式例子

享元模式,亦稱cache、flyweight
內(nèi)在狀態(tài):對(duì)象的常量數(shù)據(jù),其他對(duì)象只能讀不能改
外在狀態(tài):能“從外部”改變

享元模式將部分或全部內(nèi)在狀態(tài)抽取出來,單獨(dú)存放一個(gè)地方(共享),以減少內(nèi)存的占用,適合需要?jiǎng)?chuàng)建大量相似對(duì)象(只保留內(nèi)在狀態(tài)對(duì)象的引用)的場景。

偽代碼例子:

// 內(nèi)在狀態(tài)類,享元類
class Flyweight is
    field repeatingState

    // 可能需要根據(jù)外在狀態(tài)進(jìn)行操作
    method operation(uniqueState) is
        // 執(zhí)行操作...

// 需要?jiǎng)?chuàng)建大量相似對(duì)象的情景類,包含內(nèi)在狀態(tài)和外在狀態(tài)
class Context is
    field uniqueState
    // 只保留享元類對(duì)象引用
    filed flyweight: Flyweight

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

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

// 由工廠類根據(jù)repeatingState參數(shù)返回對(duì)應(yīng)的享元類對(duì)象
class FlyweightFactory is
    // 緩存已經(jīng)創(chuàng)建的享元類對(duì)象
    static field cache: Flyweight[]

    // 根據(jù)repeatingState參數(shù)返回對(duì)應(yīng)的享元類對(duì)象
    static method getFlyweight(repeatingState): Flyweight is
        flyweight = cache.get(repeatingState)
        if (flyweight == null)
            flyweight = new Flyweight(repeatingState)
            chache.put(repeatingState, flyweight)
        return flyweight

// Client在構(gòu)造情景類時(shí)傳入repeatingState和uniqueState參數(shù)
class Demo is
    method example() is
        context = new Context(repeatingState, uniqueState)
        context.operation()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容