Design mode Template method mode display program ape of the Day

Source: Internet
Author: User
Tags dota

Reprint Please specify source: http://blog.csdn.net/lmj623565791/article/details/26276093

Continuous design Mode ~ Template Method mode

Old routines, look high definition: It defines the skeleton of the algorithm. Although some of the steps are deferred to the child class. Without changing the algorithm structure. The steps to define the algorithm again.

Simply look at the definition, the template method defines the steps of an algorithm, and agrees that the subclass provides the implementation for one or more steps.

The definition is clear, the following sample shows the company's work (purely entertainment, if there is a similar.) Please take your seat). Brief description: The company has programmers, testing, HR, project managers and other people, the following use template method mode, record all the staff's work situation:

First, a superclass, a Workoneday method is defined in the Super class. Set as the skeleton of the algorithm:

Package Com.zhy.pattern.template;public abstract class worker{protected string Name;public Worker (string name) { THIS.name = name;} /** * Record a day's work */public final void Workoneday () {System.out.println ("-----------------working start---------------"); Entercompany (); Computeron (); work (); Computeroff (); Exitcompany (); System.out.println ("-----------------work End---------------");} /** * Working */public abstract void work ();/** * Turn off computer */private void Computeroff () {System.out.println (name + "Turn off Computer");} /** * Open Computer */private void Computeron () {System.out.println (name + "Turn on PC"); /** * Enter company */public void Entercompany () {System.out.println (name + "enter Company"); /** * Leave company */public void Exitcompany () {System.out.println (name + "leave Company");}

Defines a skeleton for work (algorithm), including the following steps:

A, enter the company

B. Turn on the computer

C. Working conditions

D. Turn off the computer

E. Leave the company

Can see, A, B, D, e we have implemented in the superclass, subclasses only realize the abstract method of work, record the daily working situation. The following types of cock wire admission:

Programmers:

Package Com.zhy.pattern.template;public class Itworker extends Worker{public itworker (String name) {super (name);} @Overridepublic void Work () {SYSTEM.OUT.PRINTLN (name + "Knock code-Bug-fix bug");}}

HR:

Package Com.zhy.pattern.template;public class Hrworker extends Worker{public hrworker (String name) {super (name);} @Overridepublic void Work () {SYSTEM.OUT.PRINTLN (name + "See CV-call-Pick up call");}}

Test personnel:

Package Com.zhy.pattern.template;public class Qaworker extends Worker{public qaworker (String name) {super (name);} @Overridepublic void Work () {SYSTEM.OUT.PRINTLN (name + "Write test example-Submit bug-Write test Example");}}

Project Manager:

Package Com.zhy.pattern.template;public class Managerworker extends Worker{public managerworker (String name) {Super ( name);} @Overridepublic void Work () {SYSTEM.OUT.PRINTLN (name + "Play DotA ...");}

Below we test:

Package Com.zhy.pattern.template;public class Test{public static void Main (string[] args) {Worker it1 = new Itworker ("Hon Yang") ; It1.workoneday (); Worker it2 = new Itworker ("Lao Zhang"); It2.workoneday (); Worker hr = new Hrworker ("Didi"); Hr.workoneday (); Worker QA = new Qaworker ("Lao Li"); Qa.workoneday (); Worker pm = new Managerworker ("Pit cargo");p m.workoneday ();}}

Output Result:

-----------------work start---------------Hon Yang into the company to open the computer hung Yang code-Test Bug-fix bug Hung Yang off the computer Yang leave the company-----------------work end---- ----------------------------work start---------------Didi into the company Didi open the computer Didi look at the resume-call-pick up the phone Didi shut down the computer Didi leave the company-----------------work End--------------------------------Work Start--------------- Lao Li into the company Old Lee Open computer old Li Write test example-Submit bug-Write test example old Li shut down computer old Li leave company-----------------work end--------------------------------work Start-- -------------Pit cargo into the company pit cargo open Computer pit cargo hit DotA ... Pit cargo off computer pit cargo leave company-----------------work end---------------

Well, congratulations, and learn a design pattern. Stencil method mode.

Below is a look at the template method pattern class diagram, and the class diagram of our program:


The template also has the option of setting hooks, such as the time to log a program ape to leave the company. We can add a hook to the superclass:

public Boolean isneedprintdate () {return false;} /** * Leave company */public void Exitcompany () {if (Isneedprintdate ()) {System.out.print (New Date (). toLocaleString () + "--"); SYSTEM.OUT.PRINTLN (name + "leave Company");

A isneedprintdate method is added to the superclass. and returns false by default, without printing time. Suppose a subclass needs to call the print time. The ability to replicate the hook method, returning True, for example, the programmer has replicated this method:

Package Com.zhy.pattern.template;public class Itworker extends Worker{public itworker (String name) {super (name);} @Overridepublic void Work () {SYSTEM.OUT.PRINTLN (name + "Knock code-Bug-fix bug");} @Overridepublic Boolean isneedprintdate () {return true;}}
Finally, let's look at the results of the test:

-----------------work start---------------Hon Yang into the company to open the computer hung Yang code-Test Bug-fix bug Hung Yang shut down the computer 2014-5-19 19:17:05--> Yang leaves the company-----------------work end---------------

All right. For hooks, the superclass can provide a default implementation or an empty implementation, and subclasses can overwrite or not overwrite. Detailed according to the needs of the set.


In the near future, write a reptile program. Using the template method mode, to share the following:

Requirement Analysis: The program needs to crawl data for a specific 20 sites, each site page returns different results, different URLs, different parameters, etc. but the crawl process is consistent.

So I was designing this:

A. Define a rule class (including: URL). Params. Request_method, and which data to return "based on selector")

B. Fetching data through rule

C. Processing of data

I have defined the skeleton of the algorithm in the above 3 steps, and B is the superclass implementation. A, C is implemented by subclasses:

Package Com.zhy.pattern.template;public Abstract class absextractinfo{/** * Crawl algorithm skeleton */public void extract () {Rule rule = ge Neraterule (); list<element> eles = getinfosbyrule (rule);d Ealresult (eles);} /** * Generates a rule * @return */public abstract rule generaterule ();/** * Crawl Implementation * @param Rule * @return */private List<eleme nt> getinfosbyrule (rule rule) {//the implements omitted}/** * handles the results of the fetch * @param results */public void Dealresult (LIST&L T element> results);}

Generaterule This approach, which happens to be the abstract method pattern in Factory mode (defines an interface for creating objects. However, subclasses decide which class to instantiate. The factory method model defers the process of instantiating classes to subclasses), assuming that you have forgotten to be able to view the design pattern of the factory model from the butcher bun.

All right, here we go, and finally, please leave a message.




Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Design mode Template method mode display program ape of the Day

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.