设计模式之模板方法模式

模板方法模式

定义:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类能够不改变一个算法的结构就可以重定义该算法的某些特定步骤。

举例:学生甲和学生乙抄写的试卷非常类似。除了答案不同之外,其余的题目全然同样。假设老师要更改题目,意味着两个人的试卷都须要更改。这样非常easy出错。怎样做才干使错误减少到最少,则须要模板方法模式。

试卷代码例如以下:

<span style="font-size:18px;">namespace _10._3_提炼代码
{
    class TestPaper
    {
        //试题1
        public void TestQuestion1()
        {
            Console.WriteLine("试题1");
            Console.WriteLine("答案:"+Answer1());
        }
        protected virtual string Answer1()
        {
            return"";
        }
        //试题2
        public void TestQuestion2()
        {
            Console.WriteLine("试题2");
            Console.WriteLine("答案:"+Answer2());
        }
        protected virtual string Answer2()
        {
            return"";
        }
        //试题3
        public void TestQuestion3()
        {
            Console.WriteLine("试题3");
                Console.WriteLine("答案:"+Answer3());
        }
        protected virtual string Answer3()
        {
            return"";
        }
    }
    
    //学生甲抄的试卷
    class TestPaperA : TestPaper
    {
        protected override string Answer1()
        {
            return "b";
        }
        protected override string Answer2()
        {
            return "c";
        }
        protected override string Answer3()
        {
            return "a";
        }
    }

    //学生乙抄的试卷
    class TestPaperB : TestPaper
    {
        protected override string Answer1()
        {
            return "c";
        }
        protected override string Answer2()
        {
            return "a";
        }
        protected override string Answer3()
        {
            return "a";
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("学生甲抄的试卷:");
            TestPaper studentA = new TestPaperA();
            studentA.TestQuestion1();
            studentA.TestQuestion2();
            studentA.TestQuestion3();
            Console.WriteLine("学生乙抄的试卷:");
            TestPaper studentB = new TestPaperB();
            studentB.TestQuestion1();
            studentB.TestQuestion2();
            studentB.TestQuestion3();

            Console.Read();
        }
    }
}
</span>
执行结果例如以下:


模板方法模式包括例如以下两个角色:
(1) AbstractClass(抽象类):在抽象类中定义了一系列基本操作(PrimitiveOperations),这些基本操作能够是详细的,也能够是抽象的,每个基本操作相应算法的一个步骤。在其子类中能够重定义或实现这些步骤。

同一时候。在抽象类中实现了一个模板方法(Template Method)。用于定义一个算法的框架,模板方法不仅能够调用在抽象类中实现的基本方法。也能够调用在抽象类的子类中实现的基本方法,还能够调用其它对象中的方法。
(2) ConcreteClass(详细子类):它是抽象类的子类。用于实如今父类中声明的抽象基本操作以完毕子类特定算法的步骤。也能够覆盖在父类中已经实现的详细基本操作。

原文地址:https://www.cnblogs.com/mfmdaoyou/p/6941491.html