享元模式,亦稱cache、flyweight
內(nèi)在狀態(tài):對象的常量數(shù)據(jù),其他對象只能讀不能改
外在狀態(tài):能“從外部”改變
享元模式將部分或全部內(nèi)在狀態(tài)抽取出來,單獨存放一個地方(共享)陪蜻,以減少內(nèi)存的占用,適合需要創(chuàng)建大量相似對象(只保留內(nèi)在狀態(tài)對象的引用)的場景贱鼻。
偽代碼例子:
// 內(nèi)在狀態(tài)類宴卖,享元類
class Flyweight is
field repeatingState
// 可能需要根據(jù)外在狀態(tài)進行操作
method operation(uniqueState) is
// 執(zhí)行操作...
// 需要創(chuàng)建大量相似對象的情景類,包含內(nèi)在狀態(tài)和外在狀態(tài)
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)
// 由工廠類根據(jù)repeatingState參數(shù)返回對應(yīng)的享元類對象
class FlyweightFactory is
// 緩存已經(jīng)創(chuàng)建的享元類對象
static field cache: Flyweight[]
// 根據(jù)repeatingState參數(shù)返回對應(yīng)的享元類對象
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)造情景類時傳入repeatingState和uniqueState參數(shù)
class Demo is
method example() is
context = new Context(repeatingState, uniqueState)
context.operation()