The 3rd chapter of the design pattern-template method pattern (Java implementation)

Source: Internet
Author: User

The 3rd chapter of the design pattern-template method pattern (Java implementation)

  "That, last time because my wife wanted to cook for me, so I did not finish to walk away 、、、 this one." This time, as before, the first benefits (factory method mode has been kicked off by the author). By the beauty of the abstract factory introduction of the application of the scene ~ Everyone welcome

Abstract Factory Application Scenario

    • A system is independent of the creation, composition, and presentation of its products.
    • When a system is to be configured by one of multiple product families.
    • When you want to emphasize the design of a series of related product objects for joint use.
    • When you provide a Product class library and just want to display their interfaces instead of implementing them.

"People want to talk about so much, next or let today's protagonist-the poet template method brother." ”

"Days gray, wild boundless, wind fog haze See Factory ~ You see your husband and wife to produce so much food, the air is not polluted, fog and haze more and more big." "Not because of the author Fish elder brother this foodie" (Abstract factory broken read. "Attis, who Wants me again". An author said finish and picked up spicy bar eat up 、、、), Next, I first introduce myself.

Self-introduction of template methods

In fact, people often use me, just don't know my name. The definition for me is as follows:

Define The skeleton of a algorithm in a operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm ' s structure. Listen to the abstract sister paper say you Do not understand Chinese, then I will translate: Define a framework for an algorithm in an operation, and defer some steps to a subclass. Enables subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.

My general-purpose class diagram is as follows:

  

The abstract class, in fact an abstract template, defines and implements a template method. This template method is generally a concrete method, it gives a top-level logical skeleton, and the logical composition of the steps in the corresponding abstract operation, deferred to the sub-class implementation.

Concreteclass implements one or more abstract methods defined by the parent class, each abstractclass can have any number of concreteclass corresponding to it, and each concreteclass can give the different implementations of these abstract methods, This makes the implementation of the top-level logic different. Okay, here's the basic situation. As the saying goes: Talk is cheap,show me the code. So next I'll implement a simple template approach pattern to deepen the understanding of ye.

Self-analysis of template methods

Gold No can't pure, nobody is perfect ~ first said that the inadequacy is my one big hobby:

    • Generally like in the abstract class declaration most abstract the most general thing attribute method, implements the class to implement the concrete thing the property and the method, I but opposite, therefore in the complex project will have the certain influence to the code reading.

Advantages:

    • Encapsulates the invariant part, extending the variable part.
    • Public code is extracted for ease of maintenance.
    • The behavior is controlled by the parent class, and the subclass is implemented.

Concrete implementation of Template method

Since to achieve, then a simple chestnut, presumably you know there are two kinds of living things, a specific activity is "eat, sleep, hit the peas." (The author presses: Peas Lay guns.) There is also a "eat, sleep, knock code." "(Program Ape Lay gun.) This is very simple and requires only one animal model, and possibly other species, defined here as animals. In order to know me clearly, first a code that is not implemented by the template method. The first thing to do is to implement the animal code: 

1  Public Abstract classanimal{2     //All creatures need to eat.3      Public Abstract voideat ();4     //and all the creatures are sleeping .5      Public Abstract voidsleep ();6     //Other Activities7      Public Abstract voidotherthing ();8     //Daily Activities9      Public Abstract voidactivities ();Ten}

Each animal has to eat, sleep, entertain, and then a summary of the day. But the specific realization of each species is different, the following first gives the "Eat and sleep to play peas" concrete implementation.

1  Public classAnimalY1extendsanimal{2 3      Public voideat () {4System.out.println ("Y1 animals eat candied fruit and spicy strips");//The thought of the author is illusory. 5     } 6      Public voidsleep () {7System.out.println ("Y1 animal sleeps on the Rope");//think of the small cage bag penalty you in the corner wall detention. 8     } 9      Public voidotherthing () {TenSYSTEM.OUT.PRINTLN ("Hit the Peas"); One     }  A  -      Public voidactivities () { -          the          This. Eat (); -          This. otherthing (); -          This. Sleep (); -  +     } -}

Next is the second creature, the concrete implementation of the program ape: 

1  Public classAnimalY2extendsanimal{2 3      Public voideat () {4System.out.println ("Eat takeout");//It 's sad, there's wood.5     } 6      Public voidsleep () {7System.out.println ("Sleeping on the station");//The eyes have been tears8     } 9      Public voidotherthing () {TenSystem.out.println ("Knock Code"); One     }  A  -      Public voidactivities () { -          the          This. Eat (); -          This. otherthing (); -          This. Sleep (); -  +     } -}
View Code

did you find anything? No? Take a closer look, is there a activities daily summary is the same? Right, this is common, naturally to appear in the abstract class, ye to remember a principle: DRY. What, Wu Bei said wrong? Ye said remember is obviously DIY? Ridiculous, Don ' t take it for granted. Wu bei means: Don ' t repeat yourself. If you find multiple repetitions in your code, then you need to think about whether your design is a problem, and if you can't explain why, then refactor it. Let's make the following changes, use the template mode to do, first modify the abstract class:

1  Public Abstract classanimal{2     //All creatures need to eat.3      Public Abstract voideat ();4     //and all the creatures are sleeping .5      Public Abstract voidsleep ();6     //Other Activities7      Public Abstract voidotherthing ();8     //Daily Activities9      Public voidactivities () {Ten          This. Eat (); One          This. otherthing (); A          This. Sleep (); -     } -}
View Code

after the abstract template method is defined, the Activies method of implementing the class can be removed specifically. Does the test class require any more? Well, that's not going to be easy. 、、、 All right, here we go.

"Cachinnation go out, my generation is basil people ~". "Sir Please, ah yuck, template Please, you have not told the scene ~ ~". I saw the template a swallow back to return. The author has been stunned (the author broken read: The legend of Kojiro Sasaki's Yan back unexpectedly let him for Shenfa, which is too 、、、)

Usage scenarios for template methods

    • One-time implementation of an invariant part of an algorithm, and the variable portion is left to the subclass implementation.
    • Controls the subclass extension.
    • The public behavior in each subclass can be extracted and placed into a common parent class.

(The author wipes The cold sweat on the head, throws into a chocolate in the mouth, the way: Fortunately this time did not have anything to go wrong ~ eats a chocolate pressure yajing), good template method to this is finished, want to know what next? and listen to tell.

the first chapter: the sequence of design patterns-UML class diagram that thing.

The second: the No. 0 Chapter of the design pattern-a singleton pattern (Java implementation)

Chapter Three: Design pattern 1th-factory method Mode (Java implementation)

Fourth: The design pattern of the 2nd Chapter-Abstract Factory mode (Java implementation)

PS: This blog welcome forwarding, but please specify the blog address and author ~

Blog Address: http://www.cnblogs.com/voidy/

Blog: http://voidy.gitcafe.com

<. ))) ≦

The 3rd chapter of the design pattern-template method pattern (Java implementation)

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.