模板方法

子类重写父类的方法,执行的是子类重写的方法

子类没有重写父类的方法,执行的是父类默认的方法

public class TemplateMethod {
    
    
    public void printMsg(String msg) {
        System.out.println("###########");
        wrapPrint(msg);
        System.out.println("###########");
    }

    protected void wrapPrint(String msg) {
        System.out.println("default");
    }
    
    public static void main(String[] args) {
        new TemplateMethod() {
            
        }.printMsg("hello world");
        
        System.out.println();
        
        new TemplateMethod() {
            @Override
            protected void wrapPrint(String msg) {
                System.out.println("$$ "+msg);
            }
        }.printMsg("hello java");
        
    }
    
    
}

如果在实际项目中,的确有这样的特殊业务场景,即有些实现并不确定,需要具体子类去实现,但是又必须在父类规定其调用顺序与场景,应如何做?采用模板方法

public abstract class Father {
    // 基本方法
    protected abstract void doSomething();

    // 基本方法
    protected abstract void doAnything();

    // 模板方法
    public void templateMethod() {
        /*
         * 调用基本方法,完成相关的逻辑
         */
        this.doAnything();
        this.doSomething();
    }

    public static void main(String[] args) {
        Son son = new Son();
        son.templateMethod();
    }
}

class Son extends Father {

    @Override
    protected void doSomething() {
        System.out.println("Son doSomething");
    }

    @Override
    protected void doAnything() {
        System.out.println("Son doAnything");
    }

}
原文地址:https://www.cnblogs.com/moris5013/p/10694572.html