什么是代理模式?
為其他對象提供一種代理以控制對這個(gè)對象的訪問。
實(shí)現(xiàn)
// 游戲玩家接口。由登陸、殺怪、升級三個(gè)方法。
type IGamePlayer interface {
// 登錄
Login(user, password string)
// 殺怪
KillBoss()
// 升級
Upgrade()
}
// 游戲玩家。正常玩家登陸、打怪、升級。
type GamePlayer struct {
name string
}
func NewGamePlayer(name string) *GamePlayer {
return &GamePlayer{name: name}
}
func (this *GamePlayer) Login(user, password string) {
fmt.Println("登錄名為: " + user + " 的超級VIP用戶 " + this.name + " 登錄成功")
}
func (this *GamePlayer) KillBoss() {
fmt.Println(this.name + " 在打怪")
}
func (this *GamePlayer) Upgrade() {
fmt.Println(this.name + " 升了1級")
}
// 游戲代練。也即代理類,用于代替玩家登陸、打怪、升級。
type GamePlayerProxy struct {
gamePlayer IGamePlayer
}
func NewGamePlayerProxy(gamePlayer IGamePlayer) *GamePlayerProxy {
return &GamePlayerProxy{gamePlayer: gamePlayer}
}
func (this *GamePlayerProxy) Login(user, password string) {
this.gamePlayer.Login(user, password)
}
func (this *GamePlayerProxy) KillBoss() {
this.gamePlayer.KillBoss()
}
func (this *GamePlayerProxy) Upgrade() {
this.gamePlayer.Upgrade()
}
func TestNewGamePlayerProxy(t *testing.T) {
// 定義一個(gè)玩家
player := NewGamePlayer("我是大帥哥")
// 定義一個(gè)代理
proxy := NewGamePlayerProxy(player)
// 開始打游戲
// 登錄
proxy.Login("YXX", "123456")
// 殺怪
proxy.KillBoss()
// 升級
proxy.Upgrade()
}
/*
=== RUN TestNewGamePlayerProxy
登錄名為: YXX 的超級VIP用戶 我是大帥哥 登錄成功
我是大帥哥 在打怪
我是大帥哥 升了1級
--- PASS: TestNewGamePlayerProxy (0.00s)
PASS
*/
優(yōu)點(diǎn)
- 職責(zé)清晰。真實(shí)的角色就是實(shí)現(xiàn)實(shí)際的業(yè)務(wù)邏輯,不用擔(dān)心其他非本職責(zé)的事務(wù);
- 高擴(kuò)展性。代理類完全可以在不做任何修改的情況下使用;
- 智能化。比如動(dòng)態(tài)代理。
缺點(diǎn)
有些類型的代理模式可能會(huì)造成請求的處理速度變慢;
實(shí)現(xiàn)代理模式需要額外的工作,有些代理模式的實(shí)現(xiàn)非常復(fù)雜。
使用場景
- 代理;
- 代練
注意
- 與適配器模式的區(qū)別:適配器模式主要改變所考慮對象的接口,而代理模式不能改變所代理類的接口;
- 與裝飾模式區(qū)別:裝飾模式是為了增強(qiáng)功能,而代理模式是為了加以控制。