How To Make Patterns Templates Program
Template Method
Intent
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
Problem
Imagine that you're creating a data mining application that analyzes corporate documents. Users feed the app documents in various formats (PDF, Md, CSV), and it tries to extract meaningful information from these docs in a uniform format.
The first version of the app could work simply with Physician files. In the post-obit version, it was able to back up CSV files. A month later, yous "taught" it to excerpt data from PDF files.
At some signal, you noticed that all 3 classes have a lot of like code. While the code for dealing with various information formats was entirely different in all classes, the lawmaking for information processing and analysis is almost identical. Wouldn't it be great to go rid of the code duplication, leaving the algorithm structure intact?
In that location was another problem related to client code that used these classes. It had lots of conditionals that picked a proper form of action depending on the class of the processing object. If all three processing classes had a common interface or a base of operations class, you'd exist able to eliminate the conditionals in client lawmaking and use polymorphism when calling methods on a processing object.
Solution
The Template Method pattern suggests that you suspension down an algorithm into a series of steps, turn these steps into methods, and put a series of calls to these methods inside a single template method. The steps may either be abstract
, or accept some default implementation. To use the algorithm, the client is supposed to provide its own bracket, implement all abstruse steps, and override some of the optional ones if needed (but not the template method itself).
Let'southward see how this volition play out in our data mining app. We can create a base of operations grade for all three parsing algorithms. This course defines a template method consisting of a series of calls to various document-processing steps.
At outset, we can declare all steps abstract
, forcing the subclasses to provide their own implementations for these methods. In our case, subclasses already have all necessary implementations, then the just thing we might need to do is adjust signatures of the methods to match the methods of the superclass.
Now, allow'due south see what we can practice to get rid of the indistinguishable code. It looks like the code for opening/closing files and extracting/parsing information is different for various data formats, so in that location's no point in touching those methods. However, implementation of other steps, such as analyzing the raw data and composing reports, is very similar, so it tin be pulled up into the base of operations course, where subclasses can share that code.
Equally you lot can encounter, nosotros've got two types of steps:
- abstract steps must be implemented by every subclass
- optional steps already take some default implementation, but still can exist overridden if needed
In that location'south another type of step, called hooks. A claw is an optional step with an empty body. A template method would work even if a hook isn't overridden. Usually, hooks are placed before and afterward crucial steps of algorithms, providing subclasses with boosted extension points for an algorithm.
Real-World Analogy
The template method approach tin can exist used in mass housing construction. The architectural program for building a standard house may comprise several extension points that would let a potential owner adjust some details of the resulting firm.
Each edifice step, such as laying the foundation, framing, building walls, installing plumbing and wiring for water and electricity, etc., tin be slightly inverse to make the resulting business firm a little fleck unlike from others.
Structure
-
The Abstruse Course declares methods that act as steps of an algorithm, as well every bit the actual template method which calls these methods in a specific order. The steps may either be declared
abstract
or have some default implementation. -
Concrete Classes can override all of the steps, but non the template method itself.
Pseudocode
In this example, the Template Method pattern provides a "skeleton" for diverse branches of bogus intelligence in a simple strategy video game.
All races in the game take almost the same types of units and buildings. Therefore you can reuse the same AI structure for diverse races, while existence able to override some of the details. With this approach, you can override the orcs' AI to make information technology more ambitious, make humans more defense-oriented, and make monsters unable to build anything. Adding a new race to the game would require creating a new AI subclass and overriding the default methods declared in the base AI form.
Applicability
Utilize the Template Method design when you want to let clients extend merely item steps of an algorithm, merely non the whole algorithm or its structure.
The Template Method lets you plow a monolithic algorithm into a series of individual steps which tin be easily extended by subclasses while keeping intact the structure defined in a superclass.
Utilize the pattern when you accept several classes that incorporate almost identical algorithms with some minor differences. Equally a result, you might need to modify all classes when the algorithm changes.
When you turn such an algorithm into a template method, you can likewise pull up the steps with similar implementations into a superclass, eliminating code duplication. Code that varies between subclasses can remain in subclasses.
How to Implement
-
Analyze the target algorithm to encounter whether you tin break it into steps. Consider which steps are mutual to all subclasses and which ones will always be unique.
-
Create the abstruse base class and declare the template method and a ready of abstruse methods representing the algorithm'southward steps. Outline the algorithm's construction in the template method by executing respective steps. Consider making the template method
final
to prevent subclasses from overriding information technology. -
It's okay if all the steps end up existence abstract. Still, some steps might benefit from having a default implementation. Subclasses don't have to implement those methods.
-
Retrieve of adding hooks between the crucial steps of the algorithm.
-
For each variation of the algorithm, create a new concrete subclass. It must implement all of the abstruse steps, merely may also override some of the optional ones.
Pros and Cons
- Yous can let clients override only certain parts of a large algorithm, making them less affected by changes that happen to other parts of the algorithm.
- You tin can pull the duplicate code into a superclass.
- Some clients may be limited by the provided skeleton of an algorithm.
- You might violate the Liskov Substitution Principle by suppressing a default step implementation via a subclass.
- Template methods tend to be harder to maintain the more steps they have.
Relations with Other Patterns
-
Factory Method is a specialization of Template Method. At the same time, a Factory Method may serve as a step in a large Template Method.
-
Template Method is based on inheritance: it lets you alter parts of an algorithm by extending those parts in subclasses. Strategy is based on composition: you tin can modify parts of the object's behavior by supplying it with different strategies that correspond to that behavior. Template Method works at the class level, so it's static. Strategy works on the object level, letting you switch behaviors at runtime.
How To Make Patterns Templates Program,
Source: https://refactoring.guru/design-patterns/template-method
Posted by: upchurchsucken.blogspot.com
0 Response to "How To Make Patterns Templates Program"
Post a Comment