一、 问题描述
设某考试试卷题目如下
- 在C#中,下列( )是正确的变量名称。
A. public B. _123 C. 9int D. ~bool - 类中某属性仅有get访问器,则该属性为()。
A. 只读属性 B. 只写属性 C. 读写属性 D. 不可读不可写的属性 - 下列选项中,()是引用类型。
A.enum类型 B. struct类型 C. string类型 D. int类型
要求:有甲乙两人抄了上题,并分别写出了答案。请模拟上述过程,使用模板方法模式写出程序。
二、 完成如下题目要求
-
画出静态图
-
写出采用该设计模式的好处
通过把不变的行为搬移到父类,去除子类中的重复代码 当不变和可变的行为同时出现在子类中时,可以将不变的行为提到父类中
- 编写代码
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";
}
}