[Headfirst design mode learning notes] 8 template method mode

Source: Internet
Author: User
Tags comparable

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

1. This mode is relatively simple. Here is an example of a bank loan application process (This is not an example in the book.):

When applying for a loan, the Bank should check the customer's affairs, for example, the customer's revenue and expenditure records, his credit records obtained from three places, other existing debt information, the stock market value of the borrower, and the expected future income analysis of the borrower. We can design the following template method:

abstract class CheckBackground {      public abstract void checkBank();    public abstract void checkCredit();    public abstract void checkLoan();    public abstract void checkStock();    public abstract void checkIncome();
Public void check (){// The template method is non-abstract and can be set to final, so that the subclass will not modify the process.Checkbank (); checkcredit (); checkloan (); checkstock (); checkincome ();}}

Our loan class can be designed as follows to implement the abstract method in the template method:

class LoanApp extends CheckBackground {    private String name;       public LoanApp(String name) {        this.name = name;    }        public String getName() {        return name;    }    public void checkBank() {        //ck acct, balance        System.out.println("check bank...");    }    public void checkCredit() {        //ck score from 3 companies        System.out.println("check credit...");    }    public void checkLoan() {        //ck other loan info        System.out.println("check other loan...");    }    public void checkStock() {        //ck how many stock values        System.out.println("check stock values...");    }    public void checkIncome() {        //ck how much a family make        System.out.println("check family income...");    }       //other methods}

2. the core idea of this model is "abstraction ". First, as a template method, it must be a method (nonsense ......), It can be used as an example of an algorithm. In the template method, each step must be completed by another method. Some methods are completed by this class, some are completed by the subclass of this class (the methods provided by the subclass must be declared as abstract in the superclass)-the template method defines an algorithm step, it also allows subclass to provide implementation for one or more steps. In essence, the template method provides an algorithm framework. The steps are fixed, and the implementation is performed by subclass. The advantage of this model is to maximize the abstract capability and minimize the changes required when the program needs to be changed or optimized. Note: Classes containing template methods are abstract.

3. can we control algorithms intelligently? For example, if this customer is a VIP customer in some cases, we do not need to check its income. In this case, we can use hook ), when necessary, "Mount" some methods ". In this way, we design the template method class:

Abstract class checkbackground {

Public abstract void checkbank ();

Public abstract void checkcredit ();

Public abstract void checkloan ();

Public abstract void checkstock ();

Public abstract void checkincome ();
Public void check () {// The template method is non-Abstract

Checkbank ();

Checkcredit ();

Checkloan ();
If (! Ischeckvip) {// use a hook. The subclass can overwrite as needed.

Checkstock ();

}

Checkincome ();

}
Public Boolean ischeckvip () {// Hook Function

Return false;
}

}

In addition to allowing the subclass to control the flow of some algorithms, the hook function also gives the subclass the opportunity to respond to some of the upcoming steps in the template method.

Note: Because the subclass must implement all abstract methods in the abstract class, the smaller the number of abstract methods, the better, this requires that you do not cut the data in the algorithm too carefully during design, and the flexibility of a program with a large granularity is limited. This requires you to weigh the balance, too much of the program design is balancing and compromise.

4. We will introduce a new OO principle-Hollywood principle:Don't call us, we will call you-don't call us, we will call you.

Under this principle, we allow lower-level components to hook ourselves to the system, and higher-level components determine when and how to use these lower-level components. We place the decision-making power in the higher-level module. That is to say, the way for senior components to treat low-level components is the rule of the bold text above. The book provides an example of coffee and tea (interestingly, coffee and tea is the name of Ding Wei's old album. I bought a genuine album when I was a freshman) to explain the relationship between the template method mode and this principle, see the original book (English version) p297. The relationship between this principle and the dependency inversion principle is that the latter gives us how to avoid using specific classes as much as possible, while using abstraction more, focusing on how to avoid dependency. The former focuses on creating an elastic design by creating frameworks and components, while preventing other classes from relying too much on them to avoid class ring dependencies. It is worth noting that the factory method is a special version of the template method.

5. Next, let's take a look at what uses this pattern in Java: array sorting method sort ()

The sort () designer wants this method to apply to all arrays, so set it to a static method. At the same time, you must implement the compartto method before using the sort method. To achieve this, the designer uses the comparable interface to provide the method declared by this interface, that is, compartto.

We now use this interface to design a duck class and try to compare the duck by weight.

Public class duck implements comparable {

String name;

Int weight;

Public duck (string name, int weight ){

This. Name = Name;

This. Weight = weight;

}

Public String tostring (){

Return name + "weighs" + weight;

}

Public int compareto (Object object ){

Duck otherduck = (duck) object;

If (this. weight <otherduck. Weight ){

Return-1;

} Else if (this. Weight = otherduck. Weight ){

Return 0;

} Else {// This. weight> otherduck. Weight

Return 1;

}

}

}

In this way, we can directly use the sort method in the array:

Import java. util. arraylist;

Import java. util. arrays;

Public class ducksorttestdrive {

Public static void main (string [] ARGs ){

Duck [] ducks = {

New duck ("Daffy", 8 ),

New duck ("Dewey", 2 ),

New duck ("Howard", 7 ),

New duck ("Louie", 2 ),

New duck ("Donald", 10 ),

New duck ("Huey", 2)

};

System. Out. println ("Before sorting :");

Display (Ducks );

Arrays. Sort (Ducks );

System. Out. println ("/nafter sorting :");

Display (Ducks );

}

Public static void display (duck [] ducks ){

For (INT I = 0; I <ducks. length; I ++ ){

System. Out. println (Ducks [I]);

}

}

}

What does this have to do with the template method?

The compareto method of the comparable interface enables the element to provide a relatively large algorithm. This is a bit like a function in our loan program that defines how to check the customer's revenue.

Let's take another two examples: swing:

Import java. AWT .*;

Import javax. Swing .*;

Public class myframe extends jframe {

Public myframe (String title ){

Super (title );

This. setdefaclocloseoperation (jframe. exit_on_close );

This. setsize (300,300 );

This. setvisible (true );

}

Public void paint (Graphics graphics) {// by default, it does not do anything. It is a hook. By overwriting this method, you can insert your code into jframe,

Super. Paint (graphics );

String MSG = "I rule !! ";

Graphics. Fig (MSG, 100,100 );

}

Public static void main (string [] ARGs ){

Myframe = new myframe ("head first design patterns ");

}

}

Applet: a specific applet uses a large number of hook functions to provide behavior.

Import java. Applet. Applet;

Import java. AWT. graphics;

Public class myapplet extends applet {

String message;

Public void Init (){

Message = "Hello world, I'm alive! ";

Repaint ();

}

Public void start (){

Message = "now I'm starting up ...";

Repaint ();

}

Public void stop (){

Message = "Oh, now I'm being stopped ...";

Repaint ();

}

Public void destroy (){

Message = "Goodbye, cruel world ";

Repaint ();

}

Public void paint (Graphics g ){

G. drawstring (message, 5, 15 );

}

}

6. Finally, let's compare the differences between the template method mode and the policy mode.

The former defines the outline of an algorithm and is a subclass (note that this is an inheritance)Define the content of some stepsIn this way, the details of the algorithm can be different, but the structure and process of the algorithm remain unchanged, and it has more control over the algorithm. The latterDefines a family of algorithms and swaps them because every algorithm is encapsulated.Therefore, the customer can easily use different algorithms (not through inheritance but interfaces), which is more flexible.

Http://v.youku.com/v_show/id_XMjU2NzA0OTI4.html online video

 

Author: gnuhpc

Source: http://www.cnblogs.com/gnuhpc/

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.