什么是外观模式
提供一个统一的接口,用来访问子系统中的一群接口,提供一个高层接口让子系统更容易使用。
实现
type Stock struct {
}
func NewStock() *Stock {
return &Stock{}
}
func (this *Stock) Buy() {
fmt.Println("Buy Stock...")
}
func (this *Stock) Sell() {
fmt.Println("Sell Stock...")
}
type NationalDebt struct {
}
func NewNationalDebt() *NationalDebt {
return &NationalDebt{}
}
func (this *NationalDebt) Buy() {
fmt.Println("Buy NationalDebt...")
}
func (this *NationalDebt) Sell() {
fmt.Println("Sell NationalDebt...")
}
type Realty struct {
}
func NewRealty() *Realty {
return &Realty{}
}
func (this *Realty) Buy() {
fmt.Println("Buy Realty...")
}
func (this *Realty) Sell() {
fmt.Println("Sell Realty...")
}
type Fund struct {
stock Stock
nationalDebt NationalDebt
realty Realty
}
func NewFund() *Fund {
return &Fund{
stock: Stock{},
nationalDebt: NationalDebt{},
realty: Realty{},
}
}
func (this *Fund) BuyFund() {
this.stock.Buy()
this.nationalDebt.Buy()
this.realty.Buy()
}
func (this *Fund) SellFund() {
this.stock.Sell()
this.nationalDebt.Sell()
this.realty.Sell()
}
func TestFund_BuyFund(t *testing.T) {
fund := NewFund()
fund.BuyFund()
fmt.Println("-----------------------分隔符----------------------")
fund.SellFund()
}
// === RUN TestFund_BuyFund
// Buy Stock...
// Buy NationalDebt...
// Buy Realty...
// -----------------------分隔符----------------------
// Sell Stock...
// Sell NationalDebt...
// Sell Realty...
// --- PASS: TestFund_BuyFund (0.00s)
// PASS
优点
- 实现了子系统与客户端之间的松耦合关系;
- 客户端屏蔽了子系统组件,减少了客户端所需处理的对象数目,并使得子系统使用起来更加容易。
缺点
- 不符合开闭原则,如果要修改某一个子系统的功能,通常外观类也要一起修改;
- 没有办法直接阻止外部不通过外观类访问子系统的功能,因为子系统类中的功能必须是公开的。
使用场景
- 设计初期阶段,应该有意识的将不同层分离,层与层之间建立外观模式;
- 开发阶段,子系统越来越复杂,增加外观模式提供一个简单的调用接口;
- 维护一个大型遗留系统的时候,可能这个系统已经非常难以维护和扩展,但又包含非常重要的功能,为其开发一个外观类,以便新系统与其交互。
网友评论