给一套试题让甲乙两人来做,代码如何实现:
代码:
试题类:
class TestPaper
{
public void TestQuestion1()
{
Console.WriteLine("屠龙刀的玄铁可能是()a.铁磨铸铁 b.马口铁 c.高速合金钢 d.碳素纤维");
}
public void TestQuestion2()
{
Console.WriteLine("产出了情花,造成() a.这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了生物圈的生态平衡 d.造成该地区沙漠化");
}
public void TestQuestion3()
{
Console.WriteLine("呕吐不止,开什么药() a.阿司匹林 b.牛黄解毒片 c.氟哌酸 d.喝大量生牛奶 e.以上全不对");
}
}
学生甲抄的试卷:
class TestPaperA:TestPaper
{
public new void TestQuestion1()
{
base.TestQuestion1();
Console.WriteLine("答案:b");
}
public new void TestQuestion2()
{
base.TestQuestion2();
Console.WriteLine("答案: b");
}
public new void TestQuestion3()
{
base.TestQuestion3();
Console.WriteLine("答案:b");
}
}
学生乙抄的试卷:
{
public new void TestQuestion1()
{
base.TestQuestion1();
Console.WriteLine("答案:b");
}
public new void TestQuestion2()
{
base.TestQuestion2();
Console.WriteLine("答案: b");
}
public new void TestQuestion3()
{
base.TestQuestion3();
Console.WriteLine("答案:b");
}
}
客户端:
static void Main(string[] args)
{
Console.WriteLine("学生甲抄的试卷:");
TestPaperA studentA = new TestPaperA();
studentA.TestQuestion1();
studentA.TestQuestion2();
studentA.TestQuestion3();
Console.WriteLine("学生乙抄的试卷:");
TestPaperB studentB = new TestPaperB();
studentB.TestQuestion1();
studentB.TestQuestion2();
studentB.TestQuestion3();
Console.WriteLine();
Console.Read();
}
分析:虽然题目实现了,但是两个学生的类中base.TestQuestion等, Console.WriteLine(答案)还有类似的代码。我们用了继承,并且肯定这个继承是有意义的,就应该要为子类的模板,所有重复的代码都应该上升到父类去,而不是让每个子类都去重复。
解决思路:当我们要完成在某一细节层次一致的一个过程或一系列步骤,但其各别步骤在更详细的层次上的实现可能不同时,我们通常考虑用模板方法模式来处理。就像这个例子,两个学生类只有答案不同,其他相同。我们可以把答案部分改为虚方法。
应用到上面的问题:
代码:
试题类,用Answer()虚方法。因为每个人的答案是不同的,让学生通过继承试卷来进行重写。
public void TestQuestion1()
{
Console.WriteLine("屠龙刀的玄铁可能是()a.铁磨铸铁 b.马口铁 c.高速合金钢 d.碳素纤维");
Console.WriteLine("答案:"+Answer1());
}
protected virtual string Answer1()
{
return "";
}
学生甲的试卷:直接写答案就好,因为父类建立了所有重复的模板
protected override string Answer1()
{
return "b";
}
客户端:将子类变量的声明改为了父类,利用了多态性,实现了代码的复用。
把
TestPaperA studentA = new TestPaperA();
改为
TestPaper studentA = new TestPaperA();
模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构可重定义该算法的某些特定步骤。
结构图:
分析:模板方法模式是通过把不变行为搬移到超类,去除子类中的重复代码来体现它的优势。
模板方法模式就是提供了一个很好的代码复用平台。有时候,会遇到如上述例子,一系列步骤构成的过程需要执行。从高层次上看是相同的,但是有些步骤的实现不同,如两个子类中只有答案不同,这是我们考虑使用模板方法模式。
当不变的和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现。通过模板方法模式把这些行为搬到单一的地方,这样就帮助子类拜托重复的不变行为的纠缠。如上述例子,把重复行为搬到父类,子类利用虚方法来实现。