Template Method pattern (JAVA) of software design pattern, design pattern java

Source: Internet
Author: User

Template Method pattern (JAVA) of software design pattern, design pattern java

What is the template method mode?

Defines the skeleton of an algorithm in an operation and delays these steps to the subclass. The template method allows the subclass to redefine certain steps of the Algorithm without changing the structure of an algorithm.

 

It's a good abstract concept. The content is not flattering. Let me illustrate it with a common example in my life.

 

It's a beverage machine. Everyone is familiar with it. There is a thing that can be seen everywhere in major malls. Here is an example. For example, if we want to drink a certain kind of beverage, just press the corresponding beverage category, the drinks come out automatically.

Here we can abstract and imagine the beverage production process in the machine (here is just a simple example, do not drill the horns)

Roughly four steps can be taken.

① Boil water ② brewed drinks ③ pour the drinks into the cup ④ add spices

For example:

Coffee: boil hot water --> Add coffee powder for brewing --> pour the drink into the cup --> Add a little sugar

Milk tea: boil hot water --> Add milk tea powder for brewing --> Add drinks to the cup --> add coconut/Pearl

It is not difficult to find that, in the process of beverage preparation, ① boiling water, ③ pouring a drink into the cup is a duplicate of work, and the preparation of which beverage is the same, that is, repeat work, we can set it as a universal operation.

We only need to care about steps 2 and 4.

As the four steps are involved in beverage preparation, we can abstract it into a "beverage template". The following is an example of the above. I will use the code to describe it.

 

DrinkTemplate. java (Template Class)

This is a template class for making drinks, that is, the base class for making all drinks.

We can encapsulate these four steps into a template method and implement the general steps in it.

To avoid inheriting its subclass to modify the overall production architecture, this method uses the final modifier, like the famous "Hollywood principle": Don't call us, we'll call you subclass to listen to the arrangement from the parent class

Because steps 2 and 4 need to be determined based on the beverage of the specific bubble, We need to delay the implementation to the subclass. The protected modifier is used here so that the subclass can be rewritten, other methods can be directly written as "dead" and modified with a private modifier, so that the Code staff can pay more attention to their work without having to consider other factors.

1 package com. lcw. template. test; 2 3 public abstract class DrinkTemplate {4 5/** abstract base class 6*7 * beverage method template 8*4 steps 1. Boiling Water 2. Brewing drinks 3. pouring drinks 4. Add seasoning 9 * because steps 1 and 3 are common steps, it is suitable for making any beverage, so you can write it to death for 10*2 and 4 steps, there are different choices for different drinks, so we can delay it to the subclass de-duplication implementation (pay attention to the access modifier) 11 */12 public final void drinkTempLate () {13 boilWater (); // boil 14 brew (); // brewed beverage 15 pourInCup (); // pour the beverage into the Cup 16 addCondiments (); // Add spices 17} 18 19 protected abstract void addCondiments (); // Add spices, because different spices are added to the beverage, you can delay it to the subclass to implement 20 21 private void pourInCup () {22 System. out. println ("pour the drink into the cup... "); 23} 24 25 protected abstract void brew (); // brewed beverage, because each beverage uses different materials, so we can delay to the subclass to implement 26 27 private void boilWater () {28 System. out. println ("boiling water in progress... "); 29} 30}

 

MakeCoffee. java (coffee)

What I can't say is that it inherits the abstract base class and rewrites its abstract method.

1 package com. lcw. template. test; 2/** 3*4 * @ author Balla _ rabbit 5 * brewed coffee 6*7 */8 public class MakeCoffee extends DrinkTemplate {9 10 @ Override11 protected void addCondiments () {12 System. out. println ("sugar... "); 13} 14 15 @ Override16 protected void brew () {17 System. out. println ("add coffee powder for brewing... "); 18} 19 20}

 

MakeMilkTea. java (brewed milk tea)

1 package com. lcw. template. test; 2/** 3 * brewed milk tea 4 * @ author Balla _ rabbit 5*6 */7 public class MakeMilkTea extends DrinkTemplate {8 9 @ Override10 protected void addCondiments () {11 System. out. println ("plus coconut... "); 12} 13 14 @ Override15 protected void brew () {16 System. out. println ("add milk tea powder for brewing... "); 17} 18 19}

 

Test. java (Test class)

1 package com. lcw. template. test; 2 3 public class Test {4 5/** 6 * @ author Balla _ rabbit 7 */8 public static void main (String [] args) {9 DrinkTemplate coffee = new MakeCoffee (); 10 coffee. drinkTempLate (); 11 System. out. println ("*******************************"); 12 DrinkTemplate milkTea = new MakeMilkTea (); 13 milkTea. drinkTempLate (); 14} 15 16}

Check the running effect:

 

Haha, is this implementation class clearly written? We only need to rewrite the methods we need to care about, which greatly improves the reusability of code.

 

But there is a problem that is revealed here. The implementation of coffee brewing is true, but some people do not need sugar when drinking coffee. What should I do?

Here we introduce a "hook" hook concept.

We can add hooks before and after a specific implementation method, just like a pre-method or post-method. Just like the log technology, we need to record logs before each business operation is completed.

In this method, we can use a Boolean to judge and give it a default value to see the specific implementation method.

DrinkTemplate. java (Template Class)

1 package com. lcw. template. test; 2 3 public abstract class DrinkTemplate {4 5/** abstract base class 6*7 * beverage method template 8*4 steps 1. Boiling Water 2. Brewing drinks 3. pouring drinks 4. Add seasoning 9 * because steps 1 and 3 are common steps, it is suitable for making any beverage, so you can write it to death for 10*2 and 4 steps, there are different choices for different drinks, so we can delay it to the subclass de-duplication implementation (pay attention to the access modifier) 11 */12 public final void drinkTempLate () {13 boilWater (); // boil 14 brew (); // brewed beverage 15 pourInCup (); // pour the beverage into the Cup 16 if (condition () = true) {// Add the seasoning if conditions permit, 17 addCondiments (); // Add seasoning 18} 19} 20 21 protected boolean condition () {22 return true; 23} 24 25 protected abstract void addCondiments (); // Add spices. Because different spices are added to the beverage, you can delay to the subclass to implement 26 27 private void pourInCup () {28 System. out. println ("pour the drink into the cup... "); 29} 30 31 protected abstract void brew (); // brewed beverage, because each beverage uses different materials, therefore, it can be delayed until the subclass implements 32 33 private void boilWater () {34 System. out. println ("boiling water in progress... "); 35} 36}

 

Test. java (Test class)

1 package com. lcw. template. test; 2 3 public class Test {4 5/** 6 * @ author Balla _ rabbit 7 */8 public static void main (String [] args) {9 DrinkTemplate coffee = new MakeCoffee (); 10 coffee. drinkTempLate (); 11 System. out. println ("coffee production is complete! "); 12 System. out. println ("*******************************"); 13 DrinkTemplate milkTea = new MakeMilkTea (); 14 milkTea. drinkTempLate (); 15 System. out. println ("milk tea is ready! "); 16} 17 18}

Let's take a look at the results. Haha, the sugar-free coffee is released ~

 

Summary:

First, let's talk about the advantages of the template method mode:

1. Good encapsulation 2. good reusability 3. Blocking details 4. Easy to maintain

The disadvantage is inheritance. in JAVA, only one parent class can be inherited.

 

Process: Analysis scenario --> step extraction --> code Reconstruction --> important and complex algorithms. The core algorithms are designed as templates.

Note:

The template method must be declared as public final.

The private method is the basic logic.

The protect abstract method is an extensible method.

Hooks make template methods more flexible

 


Java 23 design modes

There are three types of design patterns: creation, structure, and behavior.
The creation types include:
I. Singleton, Singleton mode: ensure that a class has only one instance and provide a global access point to it.
2. Abstract Factory: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
3. Factory Method: Define an interface used to create objects, and let the subclass decide which class to instantiate. Factory Method delays the instantiation of a class to the subclass.
4. Builder: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.
5. Prototype: Use a Prototype instance to specify the type of the object to be created, and copy the Prototype to create a new object.
Behavior types:
6. Iterator: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.
7. Observer: Observer mode: defines one-to-many dependencies between objects. When the status of an object changes, all objects dependent on it will be automatically updated by notification.
8. Template Method: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass, templateMethod allows the subclass to redefine a specific step without changing the structure of an algorithm.
9. Command: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests and record request logs, and supports unrecoverable operations.
10. State: allows an object to change its behavior when its internal State changes. The object seems to have changed its class.
11. Strategy: Define a series of algorithms, encapsulate them one by one, and enable them to replace each other. This mode allows algorithms to be independent of customers who use them.
12. China of Responsibility, Responsibility chain mode: Enables multiple objects to process requests to avoid coupling between the request sender and receiver.
13. Mediator: uses an intermediary object to encapsulate object interaction of some columns.
14. Visitor, Visitor mode: indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on this element without changing the element classes.
15th, Interpreter, Interpreter mode: a language is defined to define a representation of its grammar and an Interpreter. This Interpreter uses this representation to explain sentences in the language.
16. Memento: capture the internal state of an object without interrupting the object, and save the state outside the object.
There are:
17. Composite: Composite combines objects into a tree structure to represent the relationship between parts of the whole. Composite makes the use of a single object and a Composite object consistent.
18. Facade, appearance mode: provides a consistent interface for a group of interfaces in the subsystem. fa? Ade provides a high-level interface, which makes the subsystem easier to use.
19. Proxy: provides a Proxy for other objects to control access to this object.
20. Adapter: the Adapter mode converts a class of interfaces into another interface that the customer wants. The Adapter mode makes those classes unable to work together due to interface incompatibility.
21. Decrator: the Decorator mode dynamically adds some additional responsibilities to an object. In terms of the added functions, the Decorator mode is more flexible than the subclass generation mode.
22. Bridge: link the abstract Part with its implementation... the remaining full text>

What are the advantages of the software design pattern template pattern?

The Template Method Pattern Defines the algorithm skeleton in an operation, and delays some implementation steps to the subclass. The template method allows subclass to redefine some steps in the algorithm without changing the algorithm structure.
The template method mode is a simple design mode, but it is a basic technology for code reuse. It is particularly important in class libraries. It follows the principle that "abstract classes should have as many behaviors as possible, we should have as few data as possible. Methods used as templates should be defined in the parent class and abstract methods should be used in the definition of methods. However, the abstract methods of the parent class do not know how to deal with them, in practice, the specific processing is a subclass that implements specific functions in the subclass. Therefore, different subclass executions will produce different implementation results, but the processing process is customized according to the parent class. This is the essence of the template method. The algorithm skeleton is developed to implement sub-classes.

We recommend that you read an excellent book on design patterns: "software secrets-the point of design patterns" Edited by Zheng AQI. The descriptions are in place, and the instances are easy to understand!

I wish you an early learning of the design model!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.