首页 > 代码库 > 模板方法

模板方法

模板方法定义: 定义一个算法框架,将算法框架的具体实现步骤放到子类去实现,从而达到可以多样化实现过程的目的.

抽象父类:‘

public abstract class AbstractClass {
protected abstract void doSomething1();
protected abstract void doSomething2();
protected abstract void doSomething3();
public final void doTheRealThing(){
this.doSomething1();
this.doSomething2();
this.doSomething3();
}
}

实现具体方法的子类:

public class ConcreteClass1 extends AbstractClass {

@Override
protected void doSomething1() {
// TODO Auto-generated method stub
System.out.println("I am the no.1 method in class 1");
}

@Override
protected void doSomething2() {
// TODO Auto-generated method stub
System.out.println("I am the no.2 method in class 1");
}

@Override
protected void doSomething3() {
// TODO Auto-generated method stub
System.out.println("I am the no.3 method in class 1");
}
}

public class ConcreteClass2 extends AbstractClass {

@Override
protected void doSomething1() {
// TODO Auto-generated method stub
System.out.println("I am the no.1 method in class 2");
}

@Override
protected void doSomething2() {
// TODO Auto-generated method stub
System.out.println("I am the no.2 method in class 2");
}

@Override
protected void doSomething3() {
// TODO Auto-generated method stub
System.out.println("I am the no.3 method in class 2");
}

}

调用方法:

public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractClass as = new ConcreteClass1();
as.doTheRealThing();

as = new ConcreteClass2();
as.doTheRealThing();
}

模板方法比较容易理解就是在抽象父类里定义了大的算法实现和算法实现具体小的方法的定义, 小方法的具体实现 放到继承他的子类里做.达到变化适应不同需求的目的.