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

    模板方法的作用在于套用同一个模板填写不同的内容。

    这个时候要避免修好改原有内容,同时又要最少代码。

    最好的方法是父类保持不能改动的方法中使用可重写方法。

    最好的情况下是用抽象类,迫使子类必须填写父类类的抽象方法。我就不这么讲究了。我经验上看,这些适合协议类的用途,比如SOAP协议下的报文。

    //模板方法调用的答案方法会被子类重写
    public class Temple {
        public void Question1(){
            System.out.println("这是问题1");
            Answer1();
        }    
        public void Question2(){
            System.out.println("这是问题2");
            Answer2();
        }    
        public void Question3(){
            System.out.println("这是问题3");
            Answer3();
        }
        public void Answer1(){
            System.out.println("这是答案1");
        }
        public void Answer2(){
            System.out.println("这是答案2");
        }
        public void Answer3(){
            System.out.println("这是答案3");
        }
    }

    学生类1重写答案

    public class Student1 extends Temple {
        public void Answer1(){
            System.out.println("这是Student1答案1");
        }
        public void Answer2(){
            System.out.println("这是Student1答案2");
        }
        public void Answer3(){
            System.out.println("这是Student1答案3");
        }
    }

    学生类2重写答案

    public class Student2 extends Temple {
        public void Answer1(){
            System.out.println("这是Student2答案1");
        }
        public void Answer2(){
            System.out.println("这是Student2答案2");
        }
        public void Answer3(){
            System.out.println("这是Student2答案3");
        }
        
    
    }

    调用方法主线程

    public class A {
        public static void main(String[] args) {
            Temple s1=new Student1();
            Temple s2=new Student2();
            s1.Question1();
            s1.Question2();
            s1.Question3();
            s2.Question1();
            s2.Question2();
            s2.Question3();
        }
    }

    如果做过webService接口的话不妨联想下我这个东西,以后写报文是不是会非常好用。

  • 相关阅读:
    struts2学习笔记一struts2标签学习
    Struts2常用标签总结
    Strtus2标签<s:url>
    com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@d3ade7 ,项目启动错误
    【异常处理】com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@390508 --&nb
    MyEclipse怎么导入导出项目
    struts2的s:iterator 标签 详解
    CSS中的Position属性
    用Iterator实现遍历集合
    ArrayList的toArray
  • 原文地址:https://www.cnblogs.com/blackdeng/p/9184904.html
Copyright © 2011-2022 走看看