zoukankan      html  css  js  c++  java
  • 模板方法

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

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

    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");
        }
    
    }
  • 相关阅读:
    android 使用Activity做窗口弹出(模拟Dialog)
    解决ListView 跟ScroolView 共存 listItem.measure(0, 0) 空指针
    基于iview使用jsx扩展成可编辑的表格
    vue token 过期处理
    组件通信 eventtBus
    组件通信 $ref
    组件通信 Provide&&inject
    Vue 生命周期
    layui token 过期 重新登陆
    Python(3) 进制转换
  • 原文地址:https://www.cnblogs.com/moris5013/p/10694572.html
Copyright © 2011-2022 走看看