Application examples and templates mode

Model name and classification

    templateMethod
behavioral patterns

intention

    Definition of a skeleton algorithm operation, some steps to the word delay class. TemplateMethod word class may not be changed so that a structure of certain steps of the algorithm of the algorithm to redefine.

motivation

    In Maven software, we have defined three life cycle, in which the default life cycle there are many stages, compile, package, install, and so on. Maven official for each stage of the implementation have written, but more flexible software must support other third-party plug-ins. To achieve more customization features.

Remember maven project, we label Description of what we can declare a plug-in and bind to a specific lifecycle stages. Maven package for itself or install or compile intervene.
like this:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <version>1.2.1</version>
  // 任务执行,插件可以执行多个任务
  <executions>
    <execution>
        // 绑定了package阶段,很多插件不需要指定,因为插件的目标在编写时已经定义好默认绑定阶段
      <phase>package</phase>
      <goals>
        // 通过goals配置指定要执行的插件目标
        <goal>shade</goal>
      </goals>
      // 某些插件支持出传入参数,像mvn install -Dmaven.test.skip=true。里面的-D意味着
      //后面是参数,真正的参数是maven.test.skip=true,这个也可以使用configuration配置,全局生效。
      <configuration>
        <transformers>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>HelloWorld</mainClass>
          </transformer>
        </transformers>
      </configuration>
    </execution>
  </executions>
</plugin>

applicability

    In the actual design, we define the steps, but allows different implementations. Or we want our design to support a variety of different implementations.

structure

Participants

  • Parent, usually an abstract class --AbstractClass
  • Subclass of class specific methods to achieve - SubClass

cooperation

  • Parent class is defined in the template sequence process operation, and setting method final, means that the operating sequence can not be changed.
  • After the subclass inherits the parent class, rewriting real steps method
  • The perfect realization of intent: the skeleton of the parent class defined algorithm, which defines its subclasses implement some steps.

effect

Previously mentioned, we can make better scalability programming, Maven plug-way, spring custom extensions and so on.

Code examples

Example 1: Display Mode

https://www.runoob.com/design-pattern/template-pattern.html

// 步骤 1
// 创建一个抽象类,它的模板方法被设置为 final。
// Game.java
public abstract class Game {
   abstract void initialize();
   abstract void startPlay();
   abstract void endPlay();
 
   //模板
   public final void play(){
 
      //初始化游戏
      initialize();
 
      //开始游戏
      startPlay();
 
      //结束游戏
      endPlay();
   }
}

// 步骤 2
// 创建扩展了上述类的实体类。
// Cricket.java
public class Cricket extends Game {
 
   @Override
   void endPlay() {
      System.out.println("Cricket Game Finished!");
   }
 
   @Override
   void initialize() {
      System.out.println("Cricket Game Initialized! Start playing.");
   }
 
   @Override
   void startPlay() {
      System.out.println("Cricket Game Started. Enjoy the game!");
   }
}

// Football.java
public class Football extends Game {
 
   @Override
   void endPlay() {
      System.out.println("Football Game Finished!");
   }
 
   @Override
   void initialize() {
      System.out.println("Football Game Initialized! Start playing.");
   }
 
   @Override
   void startPlay() {
      System.out.println("Football Game Started. Enjoy the game!");
   }
}

// 步骤 3
// 使用 Game 的模板方法 play() 来演示游戏的定义方式。
// TemplatePatternDemo.java
public class TemplatePatternDemo {
   public static void main(String[] args) {
 
      Game game = new Cricket();
      game.play();
      System.out.println();
      game = new Football();
      game.play();      
   }
}
Example 2: Analog implemented maven plug
只实现模板方法,实际操作更加复杂,但是过程大概如此。
在我们使用mvn build时,触发此方法。而其中的各个阶段方法,可以配置自定义插件,也可以使用maven的默认插件。
// maven 的default生命周期的build阶段。
public abstract class AbstractBuild {

    public void build(){
        initialize();
        compile();
        test();
        packagee();
        integrationTest();
        deploy();
    }
    
    protected abstract void initialize();
    protected abstract void compile();
    protected abstract void test();
    protected abstract void packagee();
    protected abstract void integrationTest();
    protected abstract void deploy();
}
Example 3 spring allows custom label extension analysis
  • Background: spring has good scalability, allowing us to expand custom label, then how to achieve it is spring, this method is to resolve the underlying process.
  • This method, spring defines the resolution process, and resolve to achieve specific, defined doParse (...) method, we can override this method to resolve our own custom labels.
  • This process is the note I wrote down while reading spring source application specially note the template pattern, again at proposed. The specific resolution process is not to say .. look at his model.

@Override
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    // 在执行我们自定义的解析器中的方法之前,先执行一些准备工作,也可以叫做预解析,对beanClass、scope、lazyInit等属性的准备
   BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
   String parentName = getParentName(element);
   if (parentName != null) {
      builder.getRawBeanDefinition().setParentName(parentName);
   }
    // 这个是自定义解析器中重写的getBeanClass方法
   Class<?> beanClass = getBeanClass(element);
   if (beanClass != null) {
      builder.getRawBeanDefinition().setBeanClass(beanClass);
   }
   else {
        // 如果没有重写getBeanClass方法,就看有没有重写getBeanClassName方法;
      String beanClassName = getBeanClassName(element);
      if (beanClassName != null) {
         builder.getRawBeanDefinition().setBeanClassName(beanClassName);
      }
   }
   builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
   BeanDefinition containingBd = parserContext.getContainingBeanDefinition();
   if (containingBd != null) {
        //如果存在父类,就使用父类的scope属性
      // Inner bean definition must receive same scope as containing bean.
      builder.setScope(containingBd.getScope());
   }
   if (parserContext.isDefaultLazyInit()) {
        // 延迟懒加载
      // Default-lazy-init applies to custom bean definitions as well.
      builder.setLazyInit(true);
   }
    // 这个是我们自己写的解析器啦,还记得模版模式么!就是这个意思,在父类中定义要做的事,而将具体的实现延迟到子类;
    // 我们可以自定义很多解析器,每个解析器都有自己的解析规则。只需要复写doParse方法就好了。典型的模版模式
   doParse(element, parserContext, builder);
   return builder.getBeanDefinition();
}

Known Uses

    Above

  • maven plug-ins to achieve
  • spring custom label resolve

Guess you like

Origin www.cnblogs.com/dhcao/p/11387505.html