1.使用场景
适用于对某一类进行特定的扩展
2.例子
spring源码中,再初始化bean工厂的时候就使用了模板设计模式,通过不同的加载方法来实现特定的加载过程。
/**
* Subclasses must implement this method to perform the actual configuration load.
* The method is invoked by {@link #refresh()} before any other initialization work.
* <p>A subclass will either create a new bean factory and hold a reference to it,
* or return a single BeanFactory instance that it holds. In the latter case, it will
* usually throw an IllegalStateException if refreshing the context more than once.
* @throws BeansException if initialization of the bean factory failed
* @throws IllegalStateException if already initialized and multiple refresh
* attempts are not supported
*/
//这里的BeandFactory方法就行下面代码中的Love方法
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
3.代码实现
父类
//这是一个抽象的类,类中的抽象方法是一个钩子,
//当子类继承这个抽象类的时候可以实现自己的特有的方法,
//同时保留父类的普通方法
public abstract class fatherClazz{
public void action(){
}
public void study() {
System.out.println("====要认认真真学习====");
}
public void work() {
System.out.println("====主动承担责任====");
}
public abstract void love();
}
子类
//这里当子类继承父类的时候只需要重载父类的抽象方法,
//就可以描述自己爱妻
public class firstson Clazzextends fatherClazz {
@Override
public void love() {
System.out.println("======找肤白貌美大长腿=========");
}
}
//第二个孩子的爱情观念
public class secondSon extends fatherClazz{
@Override
public void love() {
System.out.println("======找有钱的=========");
}
}