bibi-feiniaoyuan

在基类定义算法的结构,具体实现延迟到子类。

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";
        }
    }
}
View Code
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");
        }
    }
}

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-07-10
  • 2021-12-20
  • 2021-06-18
  • 2017-11-29
  • 2022-01-21
  • 2020-02-05
  • 2021-10-04
猜你喜欢
  • 2022-01-15
  • 2021-11-12
  • 2021-06-22
  • 2021-09-22
  • 2021-12-30
  • 2021-07-02
  • 2021-05-07
相关资源
相似解决方案