欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

大话设计-模板方法模式

程序员文章站 2022-05-04 08:50:46
在基类定义算法的结构,具体实现延迟到子类。 using System; namespace ConsoleApp2 { class Program { static void Main(string[] args) { TestPaper testPaperA = new TestPaperA(); ......

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

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