模版方法( Template Method) Java
2016-06-01
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 ""; } }
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"; } }
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"; } }
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