Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The template method pattern of trespassing Java Design pattern

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Blog original address: template method pattern for trespassing Java design pattern

Template method mode

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

The translation means that by defining the framework of the algorithm, some steps can be abstracted and implemented in subclasses. The template method allows subclasses to reimplement some of the steps of the algorithm without changing the algorithm framework.

Template method pattern UML diagram UML diagram

Cdn.xitu.io/2019/4/1/169d676374d89d71?w=500&h=240&f=jpeg&s=12703 ">

Abstract class AbstractClass defines the algorithm framework templateMethod () method, in which two methods primitve1 () and primitve2 () are abstracted, and the subclass SubClass1 inherits the abstract class AbstractClass, thus implementing primitve1 () and primitve2 ().

Template method pattern role

Abstract class (AbstractClass): defines the core framework of the algorithm, and encapsulates the local algorithm behavior into steps for subclasses to implement.

Subclass (SubClass): inherits the abstract class, implements the abstract methods in the abstract class, and implements part of the logic of the algorithm.

Template method pattern source code example

Source code address: Template-method

Abstract method

First, the abstract class is defined. The handle method, the core algorithm in the abstract class AbstractProcessor, is divided into three parts. The first check parameter is implemented in the subclass, the second result is also put in the subclass implementation, and the third operation after the result is also placed in the subclass implementation.

@ Slf4jpublic abstract class AbstractProcessor {/ * logical processing * * @ param request * @ return * / public R handle (P request) {/ / 1. Check parameter log.info ("start processing, request parameter = {}", request); validRequest (request); / / 2. Get the result R response = getResponse (request); log.info ("get the result, response result = {}", response); / / 3. The processing after the result afterHandle (response); the processing after the return response;} / * result can update other businesses or process the cache * * @ param response * / protected abstract void afterHandle (R response) / * verify request parameters * * @ param request * / protected void validRequest (P request) {if (Objects.isNull (request.getToken () {throw new RuntimeException ("token cannot be empty");} if (Objects.isNull (request.getVersion () {throw new RuntimeException ("version cannot be empty") } validRequestParam (request);} / * verify the real parameter of the request * @ param request * / protected abstract void validRequestParam (P request); / * * get the result * @ param request * @ return * / protected abstract R getResponse (P request);}

Basic request

@ Data@SuperBuilder@NoArgsConstructor@AllArgsConstructorpublic class Request {private String version; private String token;}

Basic response

@ Data@SuperBuilder@NoArgsConstructor@AllArgsConstructorpublic class Response {private String msg; private int code; private boolean success;} subclass implementation

The first subclass implementation

@ Slf4jpublic class OneProcessor extends AbstractProcessor {public OneProcessor () {ProcessorFactory.putProcess ("two", this);} @ Override protected void afterHandle (OneResponse response) {log.info ("processing One result: {}", response.getOne ());} @ Override protected void validRequestParam (OneRequest request) {log.info ("verify the one parameter. Omit. ");} @ Override protected OneResponse getResponse (OneRequest request) {String name = request.getName (); return OneResponse.builder () .one (name +" one ") .success (true) .code (0) .msg (" success ") .build ();}}

The request for the first subclass

@ Data@ToString (callSuper = true) @ SuperBuilder@NoArgsConstructor@AllArgsConstructorpublic class OneRequest extends Request {private String name; @ Builder.Default private int a = 0;}

The response of the first subclass

@ Data@ToString (callSuper = true) @ SuperBuilder@NoArgsConstructor@AllArgsConstructorpublic class OneResponse extends Response {private String one;}

The second subclass implementation

@ Slf4jpublic class TwoProcessor extends AbstractProcessor {public TwoProcessor () {ProcessorFactory.putProcess ("two", this);} @ Override protected void afterHandle (TwoResponse response) {log.info ("processing result TWO, {}", response);} @ Override protected void validRequestParam (TwoRequest request) {log.info ("verify the TWO parameter. Omit. ");} @ Override protected TwoResponse getResponse (TwoRequest request) {Long id = request.getId (); return TwoResponse.builder () .two (" id is "+ id) .success (true) .code (0) .msg (" success ") .build ();}}

The request for the second subclass

@ Data@ToString (callSuper = true) @ SuperBuilder@NoArgsConstructor@AllArgsConstructorpublic class TwoRequest extends Request {private Long id;}

The response of the second subclass

@ Data@ToString (callSuper = true) @ SuperBuilder@NoArgsConstructor@AllArgsConstructorpublic class TwoResponse extends Response {private String two;} extends to factory

Sometimes when the subclass we define is defined by Spring in the Spring container, we can actually use the factory mode method to place the subclass in ProcessorFactory when the subclass is initialized, and then we only need to take it from it according to key. This method is often used in actual projects.

Public class ProcessorFactory {private static Map factories = new HashMap (); public static void putProcess (String key, AbstractProcessor process) {factories.put (key, process);} public static AbstractProcessor selectProcess (String key) {return factories.get (key) }} execute the program @ Slf4jpublic class TemplateMethodApplication {public static void main (String [] args) {OneRequest oneRequest = OneRequest.builder () .version ("2312312") .token ("23423") .name ("Zhang San") .build (); new OneProcessor () .handle (oneRequest) Log.info ("- -"); TwoRequest twoRequest = TwoRequest.builder () .version ("2312312") .token ("23423") .id (23456L) .build (); new TwoProcessor () .handle (twoRequest);}} result

Generally speaking, the framework of the algorithm is defined in the abstract class, and then some of the algorithm steps are abstracted for the implementation of the subclass. sometimes some methods can only be implemented by individual subclasses, and we can implement empty implementations in the abstract class. in the need of subclasses, we can cover the implementation of abstract classes, so as to avoid all subclasses to implement, in fact, do not care about the empty implementation. This example uses the @ SuperBuilder feature of lombok, which may cause a compilation error after downloading the complete code, because the Lombok plug-in does not support @ SuperBuilder yet.

Summary of template method pattern

Template methods are often mixed with other patterns, such as factories, policies, and so on. In fact, a large number of template method patterns are used in Spring, not just in Spring, like jdbcTemplate or RedisTemplate, like this one with Template.

Advantage 1. Encapsulate the invariant part and extend the variable part. 2. Extract the common code for easy maintenance. 3. The behavior is controlled by the parent class and implemented by the subclass.

The disadvantage is that each different implementation needs a subclass to implement, which leads to an increase in the number of classes and makes the system more large.

Using scenario 1, there are methods common to multiple subclasses and the logic is the same. 2. Important and complex methods can be considered as template methods.

Note: in order to prevent malicious operation, the general template method adds the final keyword.

Referenc

Template mode | Rookie tutorial

Template method pattern

Welcome to follow my official Wechat account.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report