国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > 模版方法( Template Method) Java

模版方法( Template Method) Java

来源:程序员人生   发布时间:2016-06-08 17:37:42 阅读次数:2112次


定义:

定义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




















生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生