設計模式Go版-裝飾器模式

----------------------------------decorator.go-------------------------------------------------

package decorator

import "fmt"

//定義公用接口
type Shower interface {
   Show()
}
//實現了公用接口的具體的類
type Person struct {
   Name string
}

func (p *Person) Show() {
   fmt.Println("裝扮的", p.Name)
}

//對Person進行裝飾,show的前後增加額外操作
type Finery struct {
   Shower
}
func (self *Finery) Decorate(component Shower) {
   self.Shower = component
}
func (self *Finery) Show() {
   if self.Shower == nil {
      return
   }
   fmt.Println("準備起牀")
   self.Shower.Show()
   fmt.Println("穿上漂亮的衣服")
}
//對Person進行裝飾,show的之後增加額外操作
type TShirts struct {
   Shower
}
func (self *TShirts) Decorate(component Shower) {
   self.Shower = component
}
func (self *TShirts) Show() {
   if self.Shower == nil {
      return
   }
   self.Shower.Show()
   fmt.Println("穿上大T恤")
}
//對Person進行裝飾,show的之後增加額外操作
type Sneakers struct {
   Shower
}
func (self *Sneakers) Decorate(component Shower) {
   self.Shower = component
}
func (self *Sneakers) Show() {
   if self.Shower == nil {
      return
   }
   self.Shower.Show()
   fmt.Println("穿上破球鞋")
}

----------------------------------decorator_test.go--------------------------------------------

package decorator

import "testing"
/**
裝飾類與要裝飾的目標實現相同的接口,並持有原始對象的引用
依據李氏替換原則,裝飾器類可以替換原始對象
而在裝飾器類的接口實現中,可以添加額外的邏輯,再進行原始對象的調用或者不調用,從而實現對原始對象所實現的接口的裝飾增強
在Java中,AOP本質上就是通過這種方式攔截函數調用,對其進行裝飾後調用裝飾之後的方法
 */
func TestDecorate(t *testing.T) {
   //最原始的功能,實現了Show接口
   xiaocai := &Person{"小菜"}

   //用以對最原始功能進行增強的新對象
   finery := &Finery{}
   tshirts := &TShirts{}
   sneakers := &Sneakers{}

   //對原始功能進行了三次裝飾增強
   finery.Decorate(xiaocai)
   tshirts.Decorate(finery)
   sneakers.Decorate(tshirts)

   //調用裝飾增強之後的實現
   sneakers.Show()
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章