新聞中心
摘要:代理模式為一個(gè)對(duì)象提供一種代理以控制對(duì)該對(duì)象的訪問。
本文分享自華為云社區(qū)《【Go實(shí)現(xiàn)】實(shí)踐GoF的23種設(shè)計(jì)模式:代理模式》,作者:元閏子 。

我們提供的服務(wù)有:成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、布爾津ssl等。為超過千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的布爾津網(wǎng)站制作公司
簡介
GoF 對(duì)代理模式(Proxy Pattern)的定義如下:
Provide a surrogate or placeholder for another object to control access to it.
也即,代理模式為一個(gè)對(duì)象提供一種代理以控制對(duì)該對(duì)象的訪問。
它是一個(gè)使用率非常高的設(shè)計(jì)模式,在現(xiàn)實(shí)生活中,也是很常見。比如,演唱會(huì)門票黃牛。假設(shè)你需要看一場(chǎng)演唱會(huì),但官網(wǎng)上門票已經(jīng)售罄,于是就當(dāng)天到現(xiàn)場(chǎng)通過黃牛高價(jià)買了一張。在這個(gè)例子中,黃牛就相當(dāng)于演唱會(huì)門票的代理,在正式渠道無法購買門票的情況下,你通過代理完成了該目標(biāo)。
從演唱會(huì)門票的例子我們也能看出,使用代理模式的關(guān)鍵在于,當(dāng) Client 不方便直接訪問一個(gè)對(duì)象時(shí),提供一個(gè)代理對(duì)象控制該對(duì)象的訪問。Client 實(shí)際上訪問的是代理對(duì)象,代理對(duì)象會(huì)將 Client 的請(qǐng)求轉(zhuǎn)給本體對(duì)象去處理。
UML 結(jié)構(gòu)
場(chǎng)景上下文
在簡單的分布式應(yīng)用系統(tǒng)(示例代碼工程)中,db 模塊用來存儲(chǔ)服務(wù)注冊(cè)和監(jiān)控信息,它是一個(gè) key-value 數(shù)據(jù)庫。為了提升訪問數(shù)據(jù)庫的性能,我們決定為它新增一層緩存:
另外,我們希望客戶端在使用數(shù)據(jù)庫時(shí),并不感知緩存的存在,這些,代理模式可以做到。
代碼實(shí)現(xiàn)
// demo/db/cache.go package db // 關(guān)鍵點(diǎn)1: 定義代理對(duì)象,實(shí)現(xiàn)被代理對(duì)象的接口 type CacheProxy struct { // 關(guān)鍵點(diǎn)2: 組合被代理對(duì)象,這里應(yīng)該是抽象接口,提升可擴(kuò)展性 db Db cache sync.Map// key為tableName,value為sync.Map[key: primaryId, value: interface{}] hit int missint } // 關(guān)鍵點(diǎn)3: 在具體接口實(shí)現(xiàn)上,嵌入代理本身的邏輯 func (c *CacheProxy) Query(tableName string, primaryKey interface{}, result interface{}) error { cache, ok := c.cache.Load(tableName) if ok { if record, ok := cache.(*sync.Map).Load(primaryKey); ok { c.hit++ result= record return nil } } c.miss++ if err := c.db.Query(tableName, primaryKey, result); err != nil { return err } cache.(*sync.Map).Store(primaryKey, result) return nil } func (c*CacheProxy) Insert(tableName string, primaryKey interface{}, record interface{}) error { if err := c.db.Insert(tableName, primaryKey, record); err != nil { return err } cache, ok := c.cache.Load(tableName) if !ok { return nil } cache.(*sync.Map).Store(primaryKey, record) return nil } ... // 關(guān)鍵點(diǎn)4: 代理也可以有自己特有方法,提供一些輔助的功能 func (c *CacheProxy) Hit() int { return c.hit } func (c*CacheProxy) Miss() int { return c.miss } ...
本文題目:實(shí)踐GoF的設(shè)計(jì)模式:代理模式
網(wǎng)站鏈接:http://m.biofuelwatch.net/article/dsoicoe.html


咨詢
建站咨詢
