代理模式,簡單來說就是提供一個對象來控制其他對象的功能。在一些情況下,一個Object不適合直接引用目標對象,但可以通過代理對象調用目標對象,起到中介代理的作用。
一、被代理的公共函數(中介是幹什麼的)
type ProxyFuncs interface {
//準備代理賣房
SailHouse()
}
二、業主要賣房
type MasterBeijing struct {
Name string //北京業主姓名
Location string //業主所賣房屋的位置
}
func (this *MasterBeijing) SailHouse() {
fmt.Printf("%s sailing house at %s\n", this.Name, this.Location)
}
三、代理業主操作賣房
type Proxier struct {
Mofbj *MasterBeijing
}
func (this *Proxier) SailHouse() {
if this.Mofbj == nil {
this.Mofbj = &MasterBeijing{}
}
this.Mofbj.SailHouse()
}
示例:中介代理業主賣方
m := &MasterBeijing{
Name: "Lao wang",
Location: "Xi Cheng",
}
proxier := &Proxier{
Mofbj: m,
}
proxier.SailHouse()
更多內容請關注每日編程,每天進步一點。
閱讀更多 每日編程 的文章