I hear you’re familiar with design patterns? How do you refactor using template patterns?

Template pattern definition

Let’s start with the definition of the template pattern.

An abstract class exposes a method/template that executes its methods. Its subclasses can override method implementations as needed, but the calls will be made in the manner defined in the abstract class. This type of design pattern is behavioral.

Maybe you read it like this

Don’t panic. Let me explain.

In my own words, a superclass abstract class defines a concrete execution flow, one or more of which are asBtrast abstract methods, leaving it up to subclasses to override the specific logic.

In the code

This is an application of the template pattern in one of my previous projects. It was used to reuse the initial logic of the player when refactoring code. Suddenly it came up and wanted to record and share a wave.

Because the company code is not convenient to attach the source code, I wrote a few classes to restore that code, than simply let you back the concept of the article to understand a lot of good, read it should not be.

A brief introduction to the situation at that time, is the project inside there are two play page, a live page, a recording page, also use a class called videoPlayer, but the two have different initialization logic, so the first version is initialized by each page itself.

1.0 Original code

Very simple two classes, the problem was a bunch of the same Settings are repeated, and some are different, so how can you refactor and encapsulate that?

Upper design pattern

2.0 Refactoring code

The whole parent of the player, push the player out, initialize it by the parent, isolate the differences using template mode.

The initPlayOption abstract method takes over the implementation of the difference part of the code.

The specific subclass inherits the parent class and overrides initPlayOption to achieve differentiation

The template pattern is as simple as that, of course, in the case where only one initPlayOption is the simplest, there can be multiple similar abstract methods.

expand

There are several similar abstract methods, typical in Android, Activity onCreate, onStart and other lifecycle methods are template mode applications.

conclusion

The template pattern is to take the different parts of the code as an abstract method, the parent class defines the execution order, and the subclass can rewrite the process of differentiation.

My personal opinion is that the definition of design mode backrest is useless and needs to be applied in the project. As I have applied it in the project before, once someone asks me, I just need to remember the application scenario at that time and I can repeat it. If I remember one of my own application scenarios, I can master it and avoid memorizing the definition.