设计模式——外观模式

2020-10-28  本文已影响0人  DevilRoshan

什么是外观模式

提供一个统一的接口,用来访问子系统中的一群接口,提供一个高层接口让子系统更容易使用。

实现

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

优点

缺点

使用场景

上一篇 下一篇

猜你喜欢

热点阅读