模板方法模式

一、 问题描述

设某考试试卷题目如下

  1. 在C#中,下列( )是正确的变量名称。
    A. public B. _123 C. 9int D. ~bool
  2. 类中某属性仅有get访问器,则该属性为()。
    A. 只读属性 B. 只写属性 C. 读写属性 D. 不可读不可写的属性
  3. 下列选项中,()是引用类型。
    A.enum类型 B. struct类型 C. string类型 D. int类型
    要求:有甲乙两人抄了上题,并分别写出了答案。请模拟上述过程,使用模板方法模式写出程序。

二、 完成如下题目要求

  1. 画出静态图
    在这里插入图片描述

  2. 写出采用该设计模式的好处

通过把不变的行为搬移到父类,去除子类中的重复代码 当不变和可变的行为同时出现在子类中时,可以将不变的行为提到父类中

  1. 编写代码
package Test;
/**
 * 主方法
 * @author Sakura
 *
 */
public class Main {
	public static void main(String[] args) {
		TestPage p1Page=new TestPageA();
		TestPage p2Page=new TestPageB();
		p1Page.testQuestion1();
		p1Page.testQuestion2();
		p1Page.testQuestion3();
		System.out.println("==================================");
		p2Page.testQuestion1();
		p2Page.testQuestion2();
		p2Page.testQuestion3();
		
	}
}package Test;
/**
 * 将公共方法提到超类
 * @author Sakura
 *
 */
public abstract class TestPage {
	public void testQuestion1() {
		System.out.println("1. 在C#中,下列( )是正确的变量名称。A. public B. _123 C. 9int D. ~bool ");
		System.out.println("答案:" + this.Answer1());
	}
	
	public void testQuestion2() {
		System.out.println("2.类中某属性仅有get访问器,则该属性为()。A. 只读属性 B. 只写属性  C. 读写属性 D. 不可读不可写的属性");
		System.out.println("答案:" + this.Answer2());
	}
	
	public void testQuestion3() {
		System.out.println("3. 下列选项中,()是引用类型。A.enum类型 B. struct类型 C. string类型 D. int类型 ");
		System.out.println("答案:" + this.Answer3());
	}
	protected String Answer2() {
		// TODO Auto-generated method stub
		return null;
	}
	protected  String Answer1() {
		// TODO Auto-generated method stub
		return null;
	}
	protected  String Answer3() {
		// TODO Auto-generated method stub
		return null;
	}
}
package Test;
/**
 * 答题人A
 * @author Sakura
 *
 */
public class TestPageA extends TestPage {

	@Override
	protected String Answer2() {
		// TODO Auto-generated method stub
		return "A";
	}

	@Override
	protected String Answer1() {
		// TODO Auto-generated method stub
		return "B";
	}

	@Override
	protected String Answer3() {
		// TODO Auto-generated method stub
		return "C";
	}
	
	
}
package Test;
/**
 * 答题人B
 * @author Sakura
 *
 */
public class TestPageB extends TestPage{
	@Override
	protected String Answer2() {
		// TODO Auto-generated method stub
		return "B";
	}

	@Override
	protected String Answer1() {
		// TODO Auto-generated method stub
		return "C";
	}

	@Override
	protected String Answer3() {
		// TODO Auto-generated method stub
		return "D";
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值