設(shè)計模式——享元模式

什么是享元模式?

運用共享技術(shù)有效地支持大量細粒度的對象。

實現(xiàn)

// 具體網(wǎng)站類
type ConcreteWebSite struct {
    name string
}

func NewConcreteWebSite(name string) *ConcreteWebSite {
    return &ConcreteWebSite{name: name}
}

func (this *ConcreteWebSite) use() {
    fmt.Println("網(wǎng)站分類:", this.name)
}

// 網(wǎng)絡(luò)工廠類
type WebSiteFactory struct {
    pool map[string]*ConcreteWebSite
}

// 獲得網(wǎng)站分類
func (this *WebSiteFactory)GetWebSiteCategory(key string) *ConcreteWebSite {
    if _, ok := this.pool[key]; !ok {
        this.pool[key] = NewConcreteWebSite(key)
    }
    return this.pool[key]
}

func (this *WebSiteFactory)GetSiteCount() int {
    return len(this.pool)
}

func NewWebSiteFactory(pool map[string]*ConcreteWebSite) *WebSiteFactory {
    return &WebSiteFactory{pool:pool}
}
func TestNewWebSiteFactory(t *testing.T) {
    factory := NewWebSiteFactory(make(map[string]*ConcreteWebSite))
    fx := factory.GetWebSiteCategory("產(chǎn)品展示")
    fx.use()
    fy:= factory.GetWebSiteCategory("產(chǎn)品展示")
    fy.use()
    fz:= factory.GetWebSiteCategory("產(chǎn)品展示")
    fz.use()
    fa:= factory.GetWebSiteCategory("博客")
    fa.use()
    fb:= factory.GetWebSiteCategory("博客")
    fb.use()
    fc:= factory.GetWebSiteCategory("博客")
    fc.use()
    fmt.Println("網(wǎng)站分類總數(shù)為: ", factory.GetSiteCount())
}
// === RUN   TestNewWebSiteFactory
// 網(wǎng)站分類: 產(chǎn)品展示
// 網(wǎng)站分類: 產(chǎn)品展示
// 網(wǎng)站分類: 產(chǎn)品展示
// 網(wǎng)站分類: 博客
// 網(wǎng)站分類: 博客
// 網(wǎng)站分類: 博客
// 網(wǎng)站分類總數(shù)為:  2
// --- PASS: TestNewWebSiteFactory (0.00s)
// PASS

優(yōu)點

  • 大大減少了對象的創(chuàng)建,降低了程序內(nèi)存的占用,提高效率。

缺點

  • 提高了系統(tǒng)的復(fù)雜度。需要分離出內(nèi)部狀態(tài)和外部狀態(tài),而外部狀態(tài)具有固化特性,不應(yīng)該隨著內(nèi)部狀態(tài)的改變而改變。

使用場景

  • 系統(tǒng)中存在大量相似對象;
  • 需要緩沖池的場景,例如:數(shù)據(jù)庫連接池。

注意

  • 注意劃分內(nèi)部狀態(tài)和外部狀態(tài),否則可能會引起線程安全問題;
  • 這些類必須有一個工廠類加以控制。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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