Golang 設計模式系列3: 組合模式(Composite design pattern)

組合結構包含一下對象:

  • Base Component(基礎組件) - 基礎組件是組合中所有對象的接口,客戶端程序使用基礎組件來處理組合中的對象。 它可以是一個接口或一個抽象類,包含一些對所有對象都是通用的方法。
  • Leaf(葉子對象) - 定義組合中元素的行爲。 它是組合的基本組成部分,並且實現了基礎組件。 它沒有對其他組件的引用。
  • Composite(組合對象) – 它由葉元素組成並實現基本組件中的操作。

組合模式基本組件定義了葉子對象和組合對象的基本通用方法。

實現

  1. Base Component(基礎組件)
    基礎組建是再組合模式中定義了最基本的行爲的組件,即在上面提到的AthleteSwimmer 等,他是指一個抽象的類應實現的方法
type Shape interface {
	Draw(fillColor string)
}
  1. Leaf(葉子對象)
    葉子對象定義了在實現基礎組件的對象的具體的行爲,比如
type Triangle struct{}

func (t *Triangle) Draw(fillColor string) {
	fmt.Println("Drawing Triangle with color", fillColor)
}

type Circle struct{}

func (t *Circle) Draw(fillColor string) {
	fmt.Println("Drawing Circle with color", fillColor)
}

  1. Composite(組合對象)
    組合對象由葉元素組成並實現基本組件中的操作。
type Drawing struct {
	shapes []Shape
}

func (d *Drawing) Add(shape Shape){
	if d.shapes == nil {
		d.shapes = make([]Shape,0)
	}
	d.shapes = append(d.shapes, shape)
}

func (d *Drawing) Draw(fillColor string) {
	for _, shape := range d.shapes {
		shape.Draw(fillColor)
	}
}

測試

func TestCompositePattern(t *testing.T) {
	triangle := &Triangle{}
	circle := &Circle{}
	drawer := Drawing{}
	drawer.Add(triangle)
	drawer.Add(circle)
	drawer.Draw("yellow")
}

測試結果

=== RUN   TestCompositePattern
Drawing Triangle with color  yellow
Drawing Circle with color  yellow
--- PASS: TestCompositePattern (0.00s)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章