Mode 13: Template method mode and its application in JDK and Tomcat

Posted by duclet on Mon, 07 Feb 2022 18:45:21 +0100

[Introduction]

We are used to taking exams. Have you ever thought about the benefits of printing test papers on a machine? Of course, it's certainly faster than handwriting first; However, the key is not to make mistakes, because everyone should have the same topics. This is the design mode of a store - the template method mode.

Template method patterns abstract a common process for a business operation and divide the process into several steps, some of which are fixed, some of which are variable, and the fixed steps are implemented by a base class, while the changed parts are implemented by hook methods with subclasses. This enables unified and standardized management of processes in the system.

1. Template Method Mode

Template Method defines the framework of algorithms in an operation and delays the implementation of these steps to subclasses. This allows subclasses to redefine certain steps of an algorithm without changing its structure. (

Among them, there are two kinds of methods: 1. Basic methods. 2. Template method (Template method is a call to the basic method, which has some logic, generally with final keywords).

UML class diagram

[Code implementation]

AbstractClass

public abstract class AbstractClass {
    public abstract void operation1();

    public abstract void operation2();

    public void TemplateMethod() {
        operation1();
        operation2();
        System.out.println("");
    }
}

ConcreteClassA class

public class ConcreteClassA extends AbstractClass {
    @Override
    public void operation1() {
        System.out.println("concrete class A Method 1 implementation");
    }

    @Override
    public void operation2() {
        System.out.println("concrete class A Method 2 implementation");
    }
}

ConcreteClassB Class

public class ConcreteClassB extends AbstractClass{
    @Override
    public void operation1() {
        System.out.println("concrete class B Method 1 implementation");
    }

    @Override
    public void operation2() {
        System.out.println("concrete class B Method 2 implementation");
    }
}

2. Scene Realization

Example: Chemistry exam paper

TestPaper class (AbstractClass class)

/**
 * Chemistry exam questions
 */
public class TestPaper {
    public void topicOne() {
        System.out.println("1,Among the following commonly used experimental instruments, the ones that cannot be used directly for separation or purification of mixtures are () \n" +
                "A.Separation funnel  B.Normal Funnel  C.Distillation flask  D.Volumetric flask ");//D
    }

    public void topicTwo() {
        System.out.println("2,The following explanation is correct () \n" +
                "A.The amount of a substance is its mass. B.Quantity of matter is an independent term. C.Moles are units of mass of matter D.Molar mass equals relative molecular mass");//B
    }

    public void topicThree() {
        System.out.println("3,The following experimental instruments are not suitable for direct heating ( )\n" +
                "A.test tube B.crucible C.Evaporating dish D.Beaker");//D
    }

}

Class A Answers

public class TestPaperA extends TestPaper{
    @Override
    public void topicOne() {
        super.topicOne();
        System.out.println("Answer: D");
    }

    @Override
    public void topicTwo() {
        super.topicTwo();
        System.out.println("Answer: B");
    }

    @Override
    public void topicThree() {
        super.topicThree();
        System.out.println("Answer: D");
    }
}

Class B Answers

public class TestPaperB extends TestPaper{
    @Override
    public void topicOne() {
        super.topicOne();
        System.out.println("Answer: D");
    }

    @Override
    public void topicTwo() {
        super.topicTwo();
        System.out.println("Answer: B");
    }

    @Override
    public void topicThree() {
        super.topicThree();
        System.out.println("Answer: D");
    }
}

Client

public class Client {
    public static void main(String[] args) {
        System.out.println("--------    A Examination papers copied by classmates    -------");
        TestPaperA A=new TestPaperA();
        A.topicOne();
        A.topicTwo();
        A.topicThree();
        System.out.println("--------    B Examination papers copied by classmates    -------");
        TestPaperB B=new TestPaperB();
        B.topicOne();
        B.topicTwo();
        B.topicThree();
    }
}

3. Scenarios, advantages and disadvantages of template approach pattern

1. Advantages

  • Template method patterns remove duplicate code from subclasses by moving unchanged behavior to the parent class.
  • Subclasses implement some of the details of the algorithm to help extend it.
  • Operations implemented by calling a subclass through a parent class add new behavior through subclass extension, which conforms to the Open-Close principle.

2. Disadvantages

  • According to design habits, abstract classes are responsible for declaring the most abstract and general properties and methods of things, and implementation classes are responsible for completing specific transaction properties and methods, but templates are the opposite. The results of subclass execution affect the results of parent classes and make code reading more difficult.

3. Application Scenarios

  • Multiple subclasses have methods in common and the logic is basically the same.
  • Important and complex algorithms can be designed as template methods, while the peripheral detailed functions are implemented by subclasses.
  • When refactoring, a template method is a commonly used method that extracts the same code into a parent class and then constrains its behavior through a constructor.

4. Examples of applications

1. Reflection of Template Method in JDK

a,JUC In AQS

AQS in JUC itself provides a set of templates for synchronization controllers through which ReentrantLock, ReentrantReadWriteLock, CountDownLatch, Semaphore, and so on can be implemented.
If you need to customize the synchronizer, the general method is to inherit AQS and override the specified method (nothing more than acquiring and releasing the state according to the rules you define); Combine AQS in the implementation of custom synchronization components and call template methods, which call overridden methods.

Methods that need to be overridden:

isHeldExclusively()//Whether the thread is exclusive to resources. Conditions are the only ones that need to be implemented.
tryAcquire(int)//Exclusive mode. Attempts to acquire resources return true for success and false for failure.
tryRelease(int)//Exclusive mode. Attempts to free resources return true for success and false for failure.
tryAcquireShared(int)//How to share. Try to get resources. Negative numbers indicate failure; 0 indicates success, but no remaining resources are available; Positive numbers indicate success with remaining resources.
tryReleaseShared(int)//How to share. Attempts to free resources return true for success and false for failure.

The above methods throw an UnsupportedOperationException exception by default. The other methods in the AQS class are final, so they cannot be used by other classes. Only these methods can be used by other classes.

b. Template methods are also heavily used in Collections

AbstractList, AbstractCollection, and so on are the parent classes of many collection classes, so some public parts are placed in abstract parent classes and some extensible methods are implemented by subclasses. Take AbstractList as an example, and AbstractList itself is a subclass of AbstractCollection:

2. Life course of tomcat

Template approach patterns are well applied in Tomcat where life cycle management involves init (initialization), start (start), stop (stop), destory (destruction) throughout the life cycle of a component, while there are fixed things to do for each life cycle stage, such as determining the pre-status and setting the post-status. And the listener who notifies the state change event, and so on, which can actually be solidified, so Tomcat solidifies the common parts of each life cycle phase, then through initInternal, startInternal, stopInternal, These hook methods are destoryInternal (In the parent class of the template method pattern, we can define a method that does nothing by default and can be overridden by subclasses as appropriate, which is called the hook method.) Open to subclasses to implement specific logic.

Explain:

  • All containers of Tomcat implement Lifecycle life cycle management interfaces, taking several core components of Tomcat as examples.
  • The abstract base class LifecycleBase implements the Lifecycle interface, among which the template interfaces such as start, stop, init are implemented.

If the article is useful to you, support it three times!!!

Topics: Java Tomcat Design Pattern