概念
装饰模式(Decorator)动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
需求
给人搭配不同的衣服
UML图
代码
人类接口
type PersonSuper interface {
Show()
}
人类实现人类接口
type Person struct {
Name string
}
func (p Person) Show() {
fmt.Printf("装扮的%v", p.Name)
fmt.Println()
}
装饰器类实现人类接口
type Decorator struct {
Person PersonSuper
}
func (d *Decorator) Show() {}
func (d *Decorator) Decorate(person PersonSuper) {
d.Person = person
}
衣服类继承装饰器类
type TShirts struct {
Decorator
}
func (t *TShirts) Show() {
t.Person.Show()
fmt.Println("大T恤")
}
func (t *TShirts) Decorate(person PersonSuper) PersonSuper {
t.Decorator.Decorate(person)
return &TShirts{
Decorator{person},
}
}
type BigTrouser struct {
Decorator
}
func (b *BigTrouser) Show() {
b.Person.Show()
fmt.Println("垮裤")
}
func (b *BigTrouser) Decorate(person PersonSuper) PersonSuper {
b.Decorator.Decorate(person)
return &BigTrouser{
Decorator{person},
}
}
type Sneakers struct {
Decorator
}
func (s *Sneakers) Show() {
s.Person.Show()
fmt.Println("破球鞋")
}
func (s *Sneakers) Decorate(person PersonSuper) PersonSuper {
s.Decorator.Decorate(person)
return &Sneakers{
Decorator{person},
}
}
.
.
.
.
测试
xc := decoratorPattern.Person{Name: "小蔡"}
fmt.Println("第一种装扮")
pqx := new(decoratorPattern.Sneakers)
kk := new(decoratorPattern.BigTrouser)
dtx := new(decoratorPattern.TShirts)
pqx.Decorate(xc)
kk.Decorate(pqx)
dtx.Decorate(kk)
dtx.Show()