zoukankan      html  css  js  c++  java
  • 模板模式

      模板模式(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中的应用。

      

      

  • 相关阅读:
    flutter开发dart基本数据类型与java、kotlin、oc、swift对照表
    flutter输入框TextField设置高度以及背景色等样式的正确姿势
    flutter开发tab页面嵌套滚动的最简洁实现方式
    flutter开发自定义ExpandListView分组列表组件
    RedisUtil-redisTemplate-setNX
    数据库无限层级分类设计
    魔方
    CountDownLatch在SpringBoot中配合@Async使用
    会话刷新Token校验流程
    Mybatis 夺命十八问,顶不住了!
  • 原文地址:https://www.cnblogs.com/lnlvinso/p/4154362.html
Copyright © 2011-2022 走看看