模版方法( Template Method) Java

来源:互联网 发布:ubuntu终端快捷键 编辑:程序博客网 时间:2024/06/04 19:05


定义:

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。


通过吧不变的行为搬移到父类,去掉子类重复代码。



类结构图:



TestPaper

package ding.study.designpatterns.templatemethod;/** * 问卷模版 和答题模板 *  * @author daniel * @email 576699909@qq.com * @time 2016-6-1 上午10:15:08 */public abstract class TestPaper {/** * 题目一 *  * @author daniel * @time 2016-6-1 上午10:15:25 */public void testQuestion1() {System.out.println("题目一");System.out.println("答案:" + getAnswer1());}/** * 答案一 *  * @author daniel * @time 2016-6-1 上午10:15:31 * @return */protected String getAnswer1() {return "";}/** * 题目二 *  * @author daniel * @time 2016-6-1 上午10:15:44 */public void testQuestion2() {System.out.println("题目二");System.out.println("答案:" + getAnswer2());}/** * 答案二 *  * @author daniel * @time 2016-6-1 上午10:15:51 * @return */protected String getAnswer2() {return "";}}

TestPaperXiaoHong

package ding.study.designpatterns.templatemethod;/** * 晓红的答卷 * @author daniel * @email 576699909@qq.com * @time 2016-6-1 上午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-6-1 上午10:17:02 */public class TestPaperXiaoMing extends TestPaper {/** * 重写父类方法 */public String getAnswer1() {return "a";}public String getAnswer2() {return "b";}}

Main调用

package ding.study.designpatterns.templatemethod;/**模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。优点通过吧不变的行为搬移到父类,去掉子类重复代码。 *  * @author daniel * @email 576699909@qq.com * @time 2016-6-1 上午10:18:55 */public class ZTestMain {/** * @author daniel * @time 2016-6-1 上午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




















1 0
原创粉丝点击