• 模板模式


      模板模式(Template Method)是较为常见的设计模式之一。

      模板模式简言之就是将公共的方法抽取到超类中,需要子类要实现的方法设置为抽象方法,由子类去完成具体的实现。

           模板方式的类图如下所示:

      

      下面是一个模板模式的例子,首先是抽象类: 

    abstract public class AbstractClass {
        public void templateMethod() {
            doOperation1();        
            doOperation2();        
            hookMethod();
        }
        
        protected abstract void doOperation1();
        
        protected abstract void doOperation2();
        
        protected void doHookMethod() { //private and final illegal
        }
    }

      下面是子类的代码:

    public class ConcreteClass extends AbstractClass {
        public void doOperation1() {
            System.out.println("doOperation1();");
        }
        
        public void doOperation2() {
            System.out.println("doOperation2();");
        }
        
        @Override
        public void doHookMethod() {
            System.out.println("This is a re-implemented hook method.");
        }
    }

      测试代码:

    public class Test {
        
        public static void main(String [ ] args) {
            AbstractClass ac = new ConcreteClass();
            ac.templateMethod();
        }
        
    }
    
    
    输出:
    doOperation1();
    doOperation2();
    This is a re-implemented hook method.

      上面例子中的doHookMethod方法也被称为钩子方法。钩子方法在抽象类中是空实现,在子类中加以扩展。钩子方法在Java中的例子是Swing中的各种Listener和对应的Adapter,Adapter中空实现了Listener中的所有方法,我们的类继承自Adapter,再扩展自己需要的方法即可。钩子方法的命名应该以do开头,这是推荐的命名规范。

      模板方式中,子类可以实现父类中未实现的部分,但是却不能修改父类中的逻辑。

        模板模式在Servlet中的应用。

      

      

  • 相关阅读:
    Git分支管理策略
    嵌入式文件系统构建工具 busybox / buildroot / openwrt
    nodejs与c语言交互应用实例
    python与c语言交互应用实例
    websocket programming base on nodejs
    Using Bluetooth LE with Go
    nodejs
    linux ipc/its
    SAMA5D3 Xplained Board
    BlueZ
  • 原文地址:https://www.cnblogs.com/lnlvinso/p/4154362.html
Copyright © 2020-2023  润新知