模板方法模式

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

模板方法模式实现考试答题:

    public abstract class TemplatePaper
    {
        public void Question()
        {
            Console.WriteLine("Question is are you ok?");
            Console.WriteLine("Answer is {0}",Answer());
        }

        public virtual string Answer()
        {
            return "";
        }
    }


    public class PaperA : TemplatePaper
    {
        public override string Answer()
        {
            return "yes";
        }
    }

    public class PaperB : TemplatePaper
    {
        public override string Answer()
        {
            return "no";
        }
    }

模板模式通过把不变的行为搬移到超类中,从而去除子类中的重复代码,提供了一个很好的代码复用平台。当不变的和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现,通过模板方法模式把这些行为搬移到单一的地方,这样就帮助子类摆脱重复的不变行为的纠缠。 

    TemplatePaper paperA = new PaperA();
    TemplatePaper paperB = new PaperB();

    paperA.Question();
    paperB.Question();    

 运行结果为: 

Question is are you ok
Answer is yes
Question is are you ok
Answer is no

原文地址:https://www.cnblogs.com/angela217/p/5408376.html