原 大話設計模式(golang) 七、模版方法模式

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

模式特點:通過吧不變的行為搬到父類,去除子類中的重複代碼。
程式執行個體:考試時使用同一種考卷(父類),不同學生上交自己填寫的試卷(子類方法的實現)

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()}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.