public class TemplateMethodDemo {
public static void main(String[] args) {
Teacher test=new Javatreacher("张三");//动态绑定
test.work();
Teacher test1=new Datatreacher("李四");
test1.work();
}
}
abstract class Teacher{
private String name;
public Teacher(String name){
this.setName(name);
}
public void prepare(){
System.out.println("准备上课");
System.out.println("打开投影仪");
}
public void end(){
System.out.println("结束上课");
System.out.println("关闭投影仪");
}
public abstract void teaching();//抽象方法,延迟到具体的子类实现
public void work(){
prepare();
teaching();
end();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Javatreacher extends Teacher{
public Javatreacher(String name) {
super(name);
}
public void teaching() {//重写父类里面的teaching()方法
System.out.println(getName()+"书写JAVA代码");
System.out.println("运行JAVA代码");
}
}
class Datatreacher extends Teacher{
public Datatreacher(String name) {
super(name);
}
public void teaching() {//重写父类里面的teaching()方法
System.out.println(this.getName()+"书写SQL语句");
System.out.println("运行SQL语句");
}
}