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

TestPaper
package ding.study.designpatterns.templatemethod;
/**
* 問(wèn)卷模版 和答題模板
*
* @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 {
/**
* 重寫(xiě)父類(lèi)方法
*/
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 {
/**
* 重寫(xiě)父類(lèi)方法
*/
public String getAnswer1() {
return "a";
}
public String getAnswer2() {
return "b";
}
}
Main調(diào)用
package ding.study.designpatterns.templatemethod;
/**
模板方法模式:定義1個(gè)操作中的算法的骨架,而將1些步驟延遲到子類(lèi)中。模板方法使得子類(lèi)可以不改變1個(gè)算法的結(jié)構(gòu)便可重定義該算法的某些特定步驟。
優(yōu)點(diǎn)
通過(guò)吧不變的行動(dòng)搬移到父類(lèi),去掉子類(lèi)重復(fù)代碼。
*
* @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("小名問(wèn)卷答案:");
TestPaper studentA=new TestPaperXiaoMing();
studentA.testQuestion1();
studentA.testQuestion2();
System.out.println("曉紅問(wèn)卷答案:");
TestPaper studentB=new TestPaperXiaoHong();
studentB.testQuestion1();
studentB.testQuestion2();
}
}
輸出結(jié)果:

源代碼:
https://github.com/dingsai88/StudyTest/tree/master/src/ding/study/designpatterns/templatemethod
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)