设计模式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()
}

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