什么是享元模式?
運用共享技術(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),否則可能會引起線程安全問題;
- 這些類必須有一個工廠類加以控制。