模板方法模式
模板方法模式(Template Method Pattern),又叫模板模式,是指定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义该算法的默写特定步骤,属于行为型设计模式。
模板方法的本质是抽象封装流程,该流程由几个步骤组成,具体步骤可以由子类进行不同实现,从而让固定得流程产生不同的结果。简单地说,就是类的继承机制,但是应用比较广泛。
角色:
- 抽象模板:定义了一套算法框架或流程;
- 具体实现:对算法框架或流程的某些步骤进行了实现
package com.jdwa.mode;
public abstract class AstractCource {
private boolean needCheckHomework = false;
public void setNeedCheckHomework(boolean needCheckHomework){
this.needCheckHomework = needCheckHomework;
}
//规定步骤,不可被重写
public final void createCource(){
postPreResource();
createNote();
liveVideo();
postHomework();
if(neekCheckHomewoork()){
checkHomework();
}
}
protected abstract void checkHomework();
protected boolean neekCheckHomewoork(){
return needCheckHomework;
}
protected void postPreResource(){
System.out.println("postPreResource====");
}
protected void createNote(){
System.out.println("ppt and note====");
}
protected void liveVideo(){
System.out.println("liveVideo====");
}
protected void postHomework(){
System.out.println("postHomework====");
}
}
package com.jdwa.mode;
public class JavaCource extends AstractCource{
@Override
protected void checkHomework() {
System.out.println("check java homework ...");
}
}
package com.jdwa.mode;
public class PythonCource extends AstractCource{
@Override
protected void checkHomework() {
System.out.println("check python homework ...");
}
}
package com.jdwa.mode;
public class Client {
public static void main(String[] args) {
System.out.println("======java cource======");
AstractCource java = new JavaCource();
java.setNeedCheckHomework(true);
java.createCource();
System.out.println("====python cource====");
AstractCource py = new PythonCource();
py.createCource();
}
}
======java cource======
postPreResource====
ppt and note====
liveVideo====
postHomework====
check java homework ...
====python cource====
postPreResource====
ppt and note====
liveVideo====
postHomework====
网友评论