Template method Mode (Template methods pattern). __java

Source: Internet
Author: User

Defined:

Defines the framework for an algorithm in an operation, and delays some steps into subclasses. So that subclasses can redefine some specific steps of the algorithm without altering the structure of an algorithm.

Note: In order to prevent malicious action, the generic template method is added to the final keyword and is not allowed to be overwritten.


Common code:

Abstract template class

Its methods are divided into two categories:

Basic methods are also called basic operations, and are methods implemented by subclasses, and are called in the template method. Template methods can have one or several, generally a specific method, that is, a framework for the implementation of the basic method of scheduling, complete the fixed logic. Public abstract class AbstractClass {//basic method protected abstract void dosomething ();//basic method protected abstract void Doany Thing (); Template method public void Templatemethod () {//Invoke the basic method to complete the associated logical this.doanything (); this.dosomething ();}} Specific template class public class ContreteClass1 extends AbstractClass {//Implementation basic method protected void doanything () {//Business logic processing} protected Voi D dosomething () {//Business logic Processing}} Scene class public class Client {public static void main (string[] args) {AbstractClass Class1 = n EW ConcreteClass1 (); Abstrcatclass Class2 = new ConcreteClass2 (); Call template Method Class1.templatemethod (); Class2.templatemethod (); Note: The basic methods in the abstract template are designed as protected types, conform to the Dimitri rule, do not need to be exposed or the method is not as protected type as possible. Implement a class if it is not necessary, try not to widen the access rights in the parent class.
Advantage: The encapsulation invariant part, the extended variable part encapsulates an algorithm that is considered to be invariant to the parent class implementation, while the variable part can continue to expand through inheritance. Extract the common part of the code, easy to maintain behavior by the parent class control, subclass implementation of the basic method is implemented by subclasses, so subclasses can expand the way to increase the corresponding function, in line with the opening and closing principles.
Disadvantage: According to our design habits, abstract class is responsible for declaring the most abstract, the most general thing attributes and methods, implementation of the class to complete the specific things properties and methods. But the template method pattern is reversed, abstract classes define some abstract methods, implemented by subclasses, and the results of subclass execution affect the result of the parent class, which has an impact on the parent class, which can make code reading difficult in complex projects, and also makes the novice feel uncomfortable.
Usage Scenario: Multiple subclasses have common methods, and the logic is basically the same. Repetitive, complex algorithm, the core algorithm can be designed as a template method, surrounding the relevant details of the functions are implemented by each subclass. When refactoring, template method patterns are often used in a pattern that extracts the same code into the parent class and then constrains its behavior through the hook function (see "Extension of the template method pattern").
Case code: Abstract Hummer Model Public abstract class Hummermodel {//First of all, the model should be able to be launched, regardless of whether it is hand-cranked, or power-driven, anyway is to be able to start, that implementation in the implementation of the class public Abstra CT void start (); You can start, you can stop, that's the real skill. Public abstract void Stop (); The horn will make a sound, is the drip bark, or beep is called public abstract void alarm (); The engine would rumble and not sound that was false public abstract void Engineboom (); The model is supposed to run. Regardless of whether people push, or power-driven, in the short run the public void run () {//Start the car This.start ();/////////////////////////////////////// When the dog is in the way, press the Horn this.alarm (); Stop at the destination This.stop (); } H1 Model Hummer model (H2 Hummer Model Code is consistent with, omitted) public class Hummerhimodel extends Hummermodel {//H1 model Hummer whistle public void alarm () {System . OUT.PRINTLN ("Hummer H1 whistle ...");} Engine roar public void Engineboom () {System.out.println ("The Hummer H1 engine sound is like this ...");} Car launch public void Start () {System.out.println ("Hummer H1 launch ...");} Parking public void Stop () {System.out.println ("Hummer H1 parking ...");} Note: In the software development process, if the same piece of code is duplicated two times, you need to be skeptical about the design, and the architect should make it clear why the same logic occurs two or more times. Scene class public class Client {public static void main (string[] args) {//XX company to H1 model Hummer Hummermodel h1 = new Hummerh1moDel (); H1 Model demo H1.run (); } }

Extension of template mode: Environment simulation: H1 model Hummer Horn wants it to ring, H2 model speakers do not have sound. Extended Abstract template class public abstract class Hummermodel {//First, the model should be able to be launched, regardless of whether it is hand-launched, or power-driven, anyway, it is to be able to start, that implementation in the implementation of the class is public abstract void Start (); You can start, you can stop, that's the real skill. Public abstract void Stop (); The horn will make a sound, is the drip bark, or beep is called public abstract void alarm (); The engine would rumble and not sound that was false public abstract void Engineboom (); The model is supposed to run. Regardless of whether people push, or power-driven, in the short run the public void run () {//Start the car This.start ();/////////////////////////////////////// When the dog is in the way, press the horn if (This.isalarm ()) {this.alarm ();
///stop at the destination This.stop (); }//Hook method, default horn is to be thought of protected Boolean isalarm () {return true;}}
Isalarm () is an implementation method. The effect is that the template method determines whether to beep the speaker based on its return value, and subclasses can override the method value. Expanded H1 Hummer public class Hummerhimodel extends Hummermodel {private Boolean alarmflag = true;//beep horn//H1 Model Hummer Whistle Public V OID Alarm () {System.out.println ("Hummer H1 whistle ...");} Engine roar public void Engineboom () {System.out.println ("The Hummer H1 engine sound is like this ...");} Car launch public void Start () {System.out.println ("Hummer H1 launch ...");} Parking public void Stop () {System.out.println ("Hummer H1 parking ...");} Protected Boolean isalarm () {Reuturn this.alarmflag;//If you want to beep, it's a client-determined public void Setalarm (Boolean isalarm) {this.al Armflag = Isalarm; H2 Hummer public class Hummer2himodel extends Hummermodel {private Boolean alarmflag = true;//to Beep horn/H1 Model Hummer Car horn Pub LIC void Alarm () {System.out.println ("Hummer H1 whistle ...");} Engine roar public void Engineboom () {System.out.println ("The Hummer H1 engine sound is like this ...");} Car launch public void Start () {System.out.println ("Hummer H1 launch ...");} Parking public void Stop () {System.out.println ("Hummer H1 parking ...");} Default no horn protected Boolean isalarm () {Reuturn FALse The return value of the Isalarm in our abstract class affects the execution result of the template method, which is called the hook method. The template method pattern is to invoke the basic method in the template method in accordance with certain rules and order, specifically to the previous example where the run () method calls other methods of this class in the order specified, and the return value of the Isalarm () method determines the execution order change in run ().
Best practice: Whether the parent class can invoke a subclass's method. The answer is yes, but the strong, extreme do not recommend doing so, then how to do it. The handle class is passed to the parameter construct of the parent class and then called. Called using reflection, you use reflection and who can't call it. The static method of the parent class that invokes the subclass. The parent class establishes a framework that, after overriding the method of the parent part, invokes a method inherited from the parent class, producing a different result (which is exactly the template method pattern). Is it possible to understand how the subclass is called by the parent class? You have modified subclasses, affected the results of the parent behavior, curve saving the way to achieve the parent class dependent subclass of the scene, template method pattern is this effect. In the XXX in action, if you need to extend the functionality, you can inherit the abstract class, then overwrite the protected method, and then invoke a similar execute method to complete your extended development, a pattern that is very easy to extend.

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.