首页 > 其他 > 详细

《大话设计模式》--模板模式

时间:2017-08-24 17:40:06      阅读:186      评论:0      收藏:0      [点我收藏+]

题目:相同的两份试卷,甲乙两个人做,答案不同

public class TestPager {
    public void question() {
        System.out.println("题目:答案是A、B、C、D中哪一个?");
        System.out.println("答案:" + answer());
    }

    protected String answer() {
        return "";
    }
}
public class TestPagerA extends TestPager {
    @Override
    protected String answer() {
        return "A";
    }
}

public class TestPagerB extends TestPager {
    @Override
    protected String answer() {
        return "B";
    }
}
public class Test {
    public static void main(String args[]) {
        System.out.println("甲的试卷");
        TestPager studentA = new TestPagerA();
        studentA.question();

        System.out.println("乙的试卷");
        TestPager studentB = new TestPagerB();
        studentB.question();
    }
}

 

打印结果:

甲的试卷
题目:答案是A、B、C、D中哪一个?
答案:A
乙的试卷
题目:答案是A、B、C、D中哪一个?
答案:B

 

这其实就是通过面向对象的三大特性实现代码的复用,使重复代码降到最低

《大话设计模式》--模板模式

原文:http://www.cnblogs.com/anni-qianqian/p/7424134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!