這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
模式特點:通過吧不變的行為搬到父類,去除子類中的重複代碼。
程式執行個體:考試時使用同一種考卷(父類),不同學生上交自己填寫的試卷(子類方法的實現)
package mainimport ("fmt")type TestPaper struct {child interface{}}func (t *TestPaper) testQuestion1() {fmt.Println("楊過得到,後來給了郭靖,練成倚天劍、屠龍刀的玄鐵可能是[] a.球磨鑄鐵 b.馬口鐵 c.高速合金鑰 d.碳素纖維")fmt.Println("答案:", t.child.(Answers).answer1())}func (t *TestPaper) testQuestion2() {fmt.Println("楊過、程英、陸無雙剷除了情花.造成[] a.使這種植物不再害人 b.使一種珍稀物種滅絕 c.破壞了那個生物圈的生態平衡 d.造成該地區沙漠化")fmt.Println("答案:", t.child.(Answers).answer2())}func (t *TestPaper) testQuestion3() {fmt.Println("藍鳳凰致使華山師徒、桃穀六仙嘔吐不止,如果你是大夫,會給他們開什麼藥[] a.阿司匹林 b.牛黃解毒片 c.氟呱酸 d.讓他們喝大量的生牛奶 e.以上全不對")fmt.Println("答案:", t.child.(Answers).answer3())}type Answers interface {answer1() stringanswer2() stringanswer3() string}type TestPaperA struct {TestPaper}func NewTestPaperA() *TestPaper {paper := &TestPaper{}var answer Answers = &TestPaperA{}paper.child = answerreturn paper}func (t *TestPaperA) answer1() string {return "b"}func (t *TestPaperA) answer2() string {return "c"}func (t *TestPaperA) answer3() string {return "a"}type TestPaperB struct {TestPaper}func NewTestPaperB() *TestPaper {paper := &TestPaper{}var answer Answers = &TestPaperB{}paper.child = answerreturn paper}func (t *TestPaperB) answer1() string {return "c"}func (t *TestPaperB) answer2() string {return "a"}func (t *TestPaperB) answer3() string {return "a"}func main() {studentA := NewTestPaperA()studentA.testQuestion1()studentA.testQuestion2()studentA.testQuestion3()studentB := NewTestPaperB()studentB.testQuestion1()studentB.testQuestion2()studentB.testQuestion3()}