zoukankan      html  css  js  c++  java
  • 模板方法模式

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

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

        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

  • 相关阅读:
    14.3.1选择选项
    14.3 选择框表单
    14.2.4HTML5约束API验证
    input标签之外是否一定添加form标签
    14.2.3自动切换焦点
    php设计模式---抽象模式模式
    php设计模式---简单工厂模式
    git基本教程,每天更新
    第5章 卷积神经网络
    第3章 深度学习基础
  • 原文地址:https://www.cnblogs.com/angela217/p/5408376.html
Copyright © 2011-2022 走看看