组合模式
职务接口
package composite
type jobber interface {
setJob(string)
setManager(jobber)
addSubordinate(jobber)
print(string)
}
职务节点
package composite
type worker struct {
job string
manager jobber
}
func (w *worker) setJob(job string) {
w.job = job
}
func (w *worker) setManager(mgr jobber) {
w.manager = mgr
}
func (w *worker) addSubordinate(subordinate jobber) {}
func (w *worker) Print(str string) {}
管理职务
package composite
import "fmt"
type composite struct {
worker
subordinate []jobber
}
func NewComposite(job string) jobber {
m := new(composite)
m.job = job
m.subordinate = make([]jobber, 0)
return m
}
func (c *composite) addSubordinate(subordinate jobber) {
subordinate.setManager(c)
c.subordinate = append(c.subordinate, subordinate)
}
func (c *composite) print(str string) {
fmt.Printf("%s %s\n", str, c.job)
str += "--"
for _, v := range c.subordinate {
v.print(str)
}
}
一般职务
package composite
import "fmt"
type leaf struct {
worker
}
func NewLeaf(job string) jobber {
l := new(leaf)
l.job = job
return l
}
func (l *leaf) print(str string) {
fmt.Printf("%s %s\n", str, l.job)
}
测试文件
package composite
import "testing"
func TestNewComposite(t *testing.T) {
m1 := NewComposite("总经理")
m2 := NewLeaf("秘书")
m3 := NewComposite("财务经理")
m4 := NewLeaf("会计")
m5 := NewLeaf("出纳")
m6 := NewComposite("研发经理")
m7 := NewComposite("前端经理")
m8 := NewLeaf("美工")
m9 := NewComposite("后端经理")
m10 := NewLeaf("程序员")
m1.addSubordinate(m2)
m1.addSubordinate(m3)
m1.addSubordinate(m6)
m3.addSubordinate(m4)
m3.addSubordinate(m5)
m6.addSubordinate(m7)
m6.addSubordinate(m9)
m7.addSubordinate(m8)
m9.addSubordinate(m10)
m1.print("")
}
标签:func,组合,模式,job,jobber,addSubordinate,subordinate,string
From: https://www.cnblogs.com/mathsmouse/p/16734699.html