title | url | tags | categories | date | ||
---|---|---|---|---|---|---|
模版方法模式 |
Template_method |
|
|
2016-07-24 06:13:30 -0700 |
把多个类公有的代码抽象出来成为一个父类,并开放接口将不同的代码交由子类来实现。
{% img /images/模版方法模式_01.png %}
public abstract class Student {//学生父类
protected void show(){
System.out.println("我的名字是:"+getName());//把公有代码抽象出来,开放一个getName()方法交给子类实现
System.out.println("我的学号是:"+getNo());//把公有代码抽象出来,开放一个getNo()方法交给子类实现
}
protected abstract String getNo();//交由子类实现
protected abstract String getName();//交由子类实现
}
public class StudentA extends Student {//学生A
protected String getNo() {
return "001";
}
protected String getName() {
return "小A";
}
}
public class StudentB extends Student {//学生B
protected String getNo() {
return "002";
}
protected String getName() {
return "小B";
}
}
public class Main{
public static void main(String[] args){
Student sa = new StudentA();
sa.show();
Student sb = new StudentB();
sb.show();
}
}