模板方法模式,定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤
特点:
type IPerson interface {
SetName(name string)
BeforeOut()
Out()
}
type Person struct {
Specific IPerson
name string
}
func (p *Person) SetName(name string) {
p.name = name
}
func (p *Person) BeforeOut() {
if p.Specific == nil {
return
}
p.Specific.BeforeOut()
}
func (p *Person) Out() {
p.BeforeOut()
fmt.Println(p.name + " go out...")
}
type Boy struct {
Person
}
func (b *Boy) BeforeOut() {
fmt.Println("get up...")
}
type Girl struct {
Person
}
func (g *Girl) BeforeOut() {
fmt.Println("get up and dress up...")
}
func main() {
person := &templateMethod.Person{}
person.Specific = &templateMethod.Boy{}
person.SetName("zhangshan")
person.Out()
fmt.Println("----------------------")
person.Specific = &templateMethod.Girl{}
person.SetName("lisi")
person.Out()
}