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

来源:互联网 发布:谷歌读屏软件下载. 编辑:程序博客网 时间:2024/05/01 05:03

请看需求概要:两个学生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";        }    }}

看看是不是又减少了代码量,从而减少了工作量。而其中只是父类中使用了虚函数,在子类中再具体实现而已。

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

原创粉丝点击