概念
模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。
需求
利用模板方法模式抄写题目并作答
UML图
代码
考试题目模板类
package templateMethod
import "fmt"
type TestPaper struct {
Answer1 func()
Answer2 func()
}
func (p *TestPaper) TestQuestion1() {
fmt.Print("1 + 1 = ? 答案:")
p.Answer1()
}
func (p *TestPaper) TestQuestion2() {
fmt.Print("1 + 2 = ? 答案:")
p.Answer2()
}
学生抄写的试卷类
package templateMethod
import "fmt"
type TestPaperA struct {
TestPaper
}
func (t TestPaperA) Answer1() {
fmt.Println(2)
}
func (t TestPaperA) Answer2() {
fmt.Println(3)
}
将考试题目模板类中作答部分延迟到其子类实现
测试
//模板方法模式
studentA := templateMethod.TestPaperA{}
studentA.TestPaper.Answer1 = studentA.Answer1
studentA.TestPaper.Answer2 = studentA.Answer2
studentA.TestQuestion1()
studentA.TestQuestion2()