JAVA设计模式:模板设计模式

1.模板设计模式,是为了体现继承的作用。它主要的作用就是在类中定义一些公共的方法和标准,而其具体的实现则叫给其子类来根据子类具体的行为来实现;因为模板设计模式中必经还有一些自己的方法不是抽象的方法,只是将一些需要交给子类的进行了抽象。这就是模板设计模式。具体的可以见如下代码:

    

  1 package com.huawei.madejin.example;
  2 
  3 abstract class Person
  4 {
  5     private String name;
  6     private int age;
  7     
  8     public Person(String name,int age){
  9         this.name = name;
 10         this.age = age;
 11     }
 12     
 13     //人都可以说话,但说的内容则根据不同的人说的内容又有所不同。
 14     public void say()
 15     {
 16         System.out.println(this.getContent());
 17     }
 18     
 19     //具体的内容,所以抽象方法,相对于一个模板
 20     public abstract String getContent();
 21     
 22     public String getName() {
 23         return name;
 24     }
 25     public void setName(String name) {
 26         this.name = name;
 27     }
 28     public int getAge() {
 29         return age;
 30     }
 31     public void setAge(int age) {
 32         this.age = age;
 33     }
 34    
 35 }
 36 
 37 class Student extends Person
 38 {
 39 
 40     private double score;
 41     
 42     
 43     public Student(String name ,int age,double score){
 44         super(name,age);
 45         this.score = score;
 46     }
 47     
 48     public double getScore() {
 49         return score;
 50     }
 51 
 52     public void setScore(double score) {
 53         this.score = score;
 54     }
 55 
 56     //子类具体去实现
 57     @Override
 58     public String getContent() {
 59         return "我是一个学生,我的名字叫:"+super.getName()+"年龄为:"+super.getAge()+"考试分数为:"+this.score;
 60     }
 61     
 62 }
 63 
 64 class Worker extends Person{
 65 
 66     private double salary;
 67     
 68     
 69     public double getSalary() {
 70         return salary;
 71     }
 72 
 73     public void setSalary(double salary) {
 74         this.salary = salary;
 75     }
 76 
 77     public Worker(String name, int age,double salary) {
 78         super(name, age);
 79         this.salary = salary;
 80         // TODO Auto-generated constructor stub
 81     }
 82 
 83     @Override
 84     public String getContent() {
 85         return "我是一名工人,我的名字叫:"+super.getName()+"年龄为:"+super.getAge()+"薪水为:"+this.salary;
 86     }
 87     
 88 }
 89 public class TemplateTest {
 90 
 91     /**
 92      * @param args
 93      */
 94     public static void main(String[] args) {
 95         // TODO Auto-generated method stub
 96         Person p = new Student("张三",18,99.0);
 97         p.say();
 98         Person pe = new Worker("李四",27,8000.0);
 99         pe.say();
100     }
101 
102 }

    模板设计可以看出现实社会中,我们经常填表的的风格一样,那个表格就是模板,具体的内容是由你来填的.......

    这就是模板设计......

原文地址:https://www.cnblogs.com/pony1223/p/3151068.html