大话设计-模板方法模式
在基类定义算法的结构,具体实现延迟到子类。
using System; namespace ConsoleApp2 { class Program { static void Main(string[] args) { TestPaper testPaperA = new TestPaperA(); testPaperA.TestQuestion1(); testPaperA.TestQuestion2(); testPaperA.TestQuestion3(); TestPaper testPaperB = new TestPaperB(); testPaperB.TestQuestion1(); testPaperB.TestQuestion2(); testPaperB.TestQuestion3(); } } class TestPaper { // 把骨架定义下来,只有答案不同,让子类实现具体答案。 public void TestQuestion1() { Console.WriteLine("题目1:XXXXXXYYYYXXXMMM"); Console.WriteLine($"题目1答案:{Answer1()}"); } protected virtual string Answer1() { return ""; } public void TestQuestion2() { Console.WriteLine("题目2:IIIPPPKKKKK"); Console.WriteLine($"题目2答案:{Answer2()}"); } protected virtual string Answer2() { return ""; } public void TestQuestion3() { Console.WriteLine("题目3:UUUUKKKKOOO"); Console.WriteLine($"题目3答案:{Answer3()}"); } protected virtual string Answer3() { return ""; } } class TestPaperA : TestPaper { protected override string Answer1() { return "a"; } protected override string Answer2() { return "b"; } protected override string Answer3() { return "c"; } } class TestPaperB : TestPaper { protected override string Answer1() { return "b"; } protected override string Answer2() { return "c"; } protected override string Answer3() { return "a"; } } }
using System; namespace ConsoleApp2 { class Program { static void Main(string[] args) { ConcreteClass concreteClass = new ConcreteClass(); concreteClass.TemplateMethod(); } } abstract class AbstractClass { public abstract void PrimitiveOperation1(); public abstract void PrimitiveOperation2(); public void TemplateMethod() { PrimitiveOperation1(); PrimitiveOperation2(); Console.WriteLine(""); } } class ConcreteClass : AbstractClass { public override void PrimitiveOperation1() { Console.WriteLine("具体操作1"); } public override void PrimitiveOperation2() { Console.WriteLine("具体操作2"); } } }
量变会引起质变。