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

《大话设计模式》Java代码示例(七)之模板方法模式

package templatemethod;

/**
 * 模板方法模式(Template Method)
 * 试卷父类
 */
public abstract class TestPaper {

    public void testQuestion1() {
        System.out.println("杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁可能是( )" +
                "  a.球墨铸铁 b.马口铁 c.高速合金钢 d.碳素纤维");
        System.out.println("答案:" + Answer1());
    }

    public void testQuestion2() {
        System.out.println("杨过、程英、陆无双铲除了情花,造成( )" +
                "  a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化");
        System.out.println("答案:" + Answer2());
    }

    public void testQuestion3() {
        System.out.println("蓝凤凰致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药( )" +
                "  a.阿司匹林 b.牛黄解毒片 c.氟哌酸 d.让他们喝大量的生牛奶 e.以上全不对");
        System.out.println("答案:" + Answer3());
    }

    protected abstract String Answer1();

    protected abstract String Answer2();

    protected abstract String Answer3();

}


package templatemethod;

/**
 * 模板方法模式(Template Method)
 * 学生A抄的试卷
 */
public class TestPaperA extends TestPaper {

    @Override
    protected String Answer1() {
        return "b";
    }

    @Override
    protected String Answer2() {
        return "c";
    }

    @Override
    protected String Answer3() {
        return "a";
    }

}
package templatemethod;

/**
 * 模板方法模式(Template Method)
 * 学生B抄的试卷
 */
public class TestPaperB extends TestPaper {

    @Override
    protected String Answer1() {
        return "c";
    }

    @Override
    protected String Answer2() {
        return "a";
    }

    @Override
    protected String Answer3() {
        return "a";
    }

}
package templatemethod;

/**
 * 模板方法模式(Template Method)
 * 客户端main方法
 */
public class Client {

    public static void main(String[] args) {
        System.out.println("学生A抄的试卷:");
        TestPaper studentA = new TestPaperA();
        studentA.testQuestion1();
        studentA.testQuestion2();
        studentA.testQuestion3();

        System.out.println("学生B抄的试卷:");
        TestPaper studentB = new TestPaperB();
        studentB.testQuestion1();
        studentB.testQuestion2();
        studentB.testQuestion3();

    }

}

 

相关文章:

  • 2021-07-02
  • 2022-01-15
  • 2021-11-12
  • 2021-07-12
  • 2021-06-08
  • 2021-12-12
  • 2021-10-14
  • 2021-09-07
猜你喜欢
  • 2021-10-01
  • 2022-01-16
  • 2021-09-24
  • 2021-12-30
  • 2021-06-22
  • 2022-01-10
  • 2017-11-29
相关资源
相似解决方案