网推软件,seo网站设计就业前景,小程序源码下载网,柯桥网站建设书生商友一、简介
代理模式#xff08;Proxy Design Pattern#xff09;在不改变原始类#xff08;或叫被代理类#xff09;代码的情况下#xff0c;通过引入代理类来给原始类附加功能。
二、优点
关注点分离访问控制延迟实例化远程访问缓存增加附加功能
三、应用场景
访问控…一、简介
代理模式Proxy Design Pattern在不改变原始类或叫被代理类代码的情况下通过引入代理类来给原始类附加功能。
二、优点
关注点分离访问控制延迟实例化远程访问缓存增加附加功能
三、应用场景
访问控制缓存保护代理远程对象智能引用其他日志记录、监控和审计等
四、UML类图 五、案例
银行提供存款和取款两种功能不同权限的用户功能不同只有管理权限的账号能存取款普通用户只能存款。
package mainimport fmttype BankAccount interface {Deposit(amount float64)Withdraw(amount float64)
}type RealBankAccount struct {Balance float64
}func NewRealBankAccount(initialBalance float64) RealBankAccount {return RealBankAccount{Balance: initialBalance}
}func (rba *RealBankAccount) Deposit(amount float64) {rba.Balance amountfmt.Printf(Deposited: %v, new balance: %v\n, amount, rba.Balance)
}func (rba *RealBankAccount) Withdraw(amount float64) {if rba.Balance amount {rba.Balance - amountfmt.Printf(Withdrew: %v, new balance: %v\n, amount, rba.Balance)} else {fmt.Printf(Insufficient balance\n)}
}type BankAccountProxy struct {UserRole stringRealBankAccount RealBankAccount
}func NewBankAccountProxy(userRole string, initialBalance float64) BankAccountProxy {return BankAccountProxy{UserRole: userRole, RealBankAccount: NewRealBankAccount(initialBalance)}
}func (proxy *BankAccountProxy) Deposit(amount float64) {if proxy.UserRole Admin || proxy.UserRole User {proxy.RealBankAccount.Deposit(amount)} else {fmt.Printf(Unauthorized access\n)}
}func (proxy *BankAccountProxy) Withdraw(amount float64) {if proxy.UserRole Admin {proxy.RealBankAccount.Withdraw(amount)} else {fmt.Printf(Unauthorized access\n)}
}func main() {adminBankAccount : NewBankAccountProxy(Admin, 1000)adminBankAccount.Deposit(500)adminBankAccount.Withdraw(200)userBankAccount : NewBankAccountProxy(User, 1000)userBankAccount.Deposit(500)userBankAccount.Withdraw(200)
}