利用虚函数和继承之模板模式

本文通过实例展示了如何在编程中通过继承和虚拟函数来减少代码量,提高工作效率。以模板方法模式为例,详细说明了如何在父类中定义公共方法,并在子类中实现特定的功能,从而避免重复代码的编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请看需求概要:两个学生A和B,对于一道题进行了解答,要打印出他们对这两道题的解答答案。

最菜鸟的代码应该是定义一个类,里面写两个方法,分别在各自方法中具体实现打印题目和答案,这个就不附上了,看看稍稍改进了点的代码:

using System; using System.Collections.Generic; using System.Text; namespace 模板方法模式一级 { class Program { static void Main(string[] args) { Console.WriteLine("学生甲抄的试卷:"); TestPaperA studentA = new TestPaperA(); studentA.TestQuestion(); Console.WriteLine("学生乙抄的试卷:"); TestPaperB studentB = new TestPaperB(); studentB.TestQuestion(); Console.Read(); } } //金庸小说考题试卷 class TestPaper { public void TestQuestion() { Console.WriteLine(" 杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁可能是[ ] a.球磨铸铁 b.马口铁 c.高速合金钢 d.碳素纤维 "); } } class TestPaperA : TestPaper { public new void TestQuestion() { base.TestQuestion1(); Console.WriteLine("答案:b"); } } class TestPaperB : TestPaper { public new void TestQuestion() { base.TestQuestion1(); Console.WriteLine("答案:a"); } } }
这里用到了继承,从工作量上,将打印题目的方法写在父类里,子类继承后直接一个base.TestQuestion()就可实现打印题目,少了重复的打题目的代码。

可是看看,是不是还有重复的地方。恩,“答案:"这个单词在代码中出现了两次并且只是跟在其后的有一点不同罢了。于是又产生了以下的代码:

using System; using System.Collections.Generic; using System.Text; namespace 模板方法模式二级 { class Program { static void Main(string[] args) { Console.WriteLine("学生甲抄的试卷:"); TestPaper studentA = new TestPaperA(); studentA.TestQuestion(); Console.WriteLine("学生乙抄的试卷:"); TestPaper studentB = new TestPaperB(); studentB.TestQuestion(); Console.Read(); } } class TestPaper { public void TestQuestion() { Console.WriteLine(" 杨过得到,后来给了郭靖,炼成倚天剑、屠龙刀的玄铁可能是[ ] a.球磨铸铁 b.马口铁 c.高速合金钢 d.碳素纤维 "); Console.WriteLine("答案:" + Answer1()); } protected virtual string Answer1() { return ""; } } //学生甲抄的试卷 class TestPaperA : TestPaper { protected override string Answer1() { return "b"; } } //学生乙抄的试卷 class TestPaperB : TestPaper { protected override string Answer1() { return "c"; } } }
看看是不是又减少了代码量,从而减少了工作量。而其中只是父类中使用了虚函数,在子类中再具体实现而已。

搞编程的孩子们都是朝着一个目的进行的:在代码安全没什么影响的情况下,向着最少量代码的方向前进。我们就不用敲嫩多代码,手疼~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值