模板模式,模板定义一些方法,作为子类实现的虚方法(对客户端隐藏),并提供一个客户端一个统一方法,这个方法调用了相关虚方法,这样,我们就像实现一个模板一样按部就班的实现一个类了。
package template;
/**
* 模板模式,这是一个汽车模板.
* @author wwe
*
*/
public abstract class CarTemplate {
/**
* 创造骨架,注意,因为建造函数不想暴露给客户端,这里用protected
* 进行修饰.
*/
protected abstract void bulidSkeleton();
/**
* 安装引擎.
*/
protected abstract void installEngine();
/**
* 安装车门.
*/
protected abstract void installDoor();
public void buildCar() {
bulidSkeleton();
installEngine();
installDoor();
}
}
package template;
public class FerrariEnzo extends CarTemplate{
@Override
protected void bulidSkeleton() {
System.out.println("FerrariEnzo's skeleton has been built!");
}
@Override
protected void installEngine() {
System.out.println("FerrariEnzo's engine has been installed!");
}
@Override
protected void installDoor() {
System.out.println("FerrariEnzo's doors have been installed!");
}
}
package template;
public class Porsches911 extends CarTemplate{
@Override
protected void bulidSkeleton() {
System.out.println("Porches911's skeleton has been built!");
}
@Override
protected void installEngine() {
System.out.println("Porches911's engine has been installed!");
}
@Override
protected void installDoor() {
System.out.println("Porches911's doors have been installed!");
}
}
package template;
public class Client {
public static void main(String[] args) {
CarTemplate Enzo = new FerrariEnzo();
Enzo.buildCar();
CarTemplate _911 = new Porsches911();
_911.buildCar();
}
}
执行结果
FerrariEnzo's engine has been installed!
FerrariEnzo's doors have been installed!
Porches911's skeleton has been built!
Porches911's engine has been installed!
Porches911's doors have been installed!