模版方法( Template Method) Java
來源:程序員人生 發布時間:2016-06-08 17:37:42 閱讀次數:2517次
定義:
定義1個操作中的算法的骨架,而將1些步驟延遲到子類中。模板方法使得子類可以不改變1個算法的結構便可重定義該算法的某些特定步驟。
通過吧不變的行動搬移到父類,去掉子類重復代碼。
類結構圖:

TestPaper
package ding.study.designpatterns.templatemethod;
/**
* 問卷模版 和答題模板
*
* @author daniel
* @email 576699909@qq.com
* @time 2016⑹⑴ 上午10:15:08
*/
public abstract class TestPaper {
/**
* 題目1
*
* @author daniel
* @time 2016⑹⑴ 上午10:15:25
*/
public void testQuestion1() {
System.out.println("題目1");
System.out.println("答案:" + getAnswer1());
}
/**
* 答案1
*
* @author daniel
* @time 2016⑹⑴ 上午10:15:31
* @return
*/
protected String getAnswer1() {
return "";
}
/**
* 題目2
*
* @author daniel
* @time 2016⑹⑴ 上午10:15:44
*/
public void testQuestion2() {
System.out.println("題目2");
System.out.println("答案:" + getAnswer2());
}
/**
* 答案2
*
* @author daniel
* @time 2016⑹⑴ 上午10:15:51
* @return
*/
protected String getAnswer2() {
return "";
}
}
TestPaperXiaoHong
package ding.study.designpatterns.templatemethod;
/**
* 曉紅的答卷
* @author daniel
* @email 576699909@qq.com
* @time 2016⑹⑴ 上午10:17:37
*/
public class TestPaperXiaoHong extends TestPaper {
/**
* 重寫父類方法
*/
public String getAnswer1() {
return "c";
}
public String getAnswer2() {
return "d";
}
}
TestPaperXiaoMing
package ding.study.designpatterns.templatemethod;
/**
* 小名的卷子答卷
*
* @author daniel
* @email 576699909@qq.com
* @time 2016⑹⑴ 上午10:17:02
*/
public class TestPaperXiaoMing extends TestPaper {
/**
* 重寫父類方法
*/
public String getAnswer1() {
return "a";
}
public String getAnswer2() {
return "b";
}
}
Main調用
package ding.study.designpatterns.templatemethod;
/**
模板方法模式:定義1個操作中的算法的骨架,而將1些步驟延遲到子類中。模板方法使得子類可以不改變1個算法的結構便可重定義該算法的某些特定步驟。
優點
通過吧不變的行動搬移到父類,去掉子類重復代碼。
*
* @author daniel
* @email 576699909@qq.com
* @time 2016⑹⑴ 上午10:18:55
*/
public class ZTestMain {
/**
* @author daniel
* @time 2016⑹⑴ 上午10:18:00
* @param args
*/
public static void main(String[] args) {
System.out.println("小名問卷答案:");
TestPaper studentA=new TestPaperXiaoMing();
studentA.testQuestion1();
studentA.testQuestion2();
System.out.println("曉紅問卷答案:");
TestPaper studentB=new TestPaperXiaoHong();
studentB.testQuestion1();
studentB.testQuestion2();
}
}
輸出結果:

源代碼:
https://github.com/dingsai88/StudyTest/tree/master/src/ding/study/designpatterns/templatemethod
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈