Touch Plate mode and hooks

Source: Internet
Author: User

Often there are multiple subclasses in the program that have common methods that have similar calling procedures. At this time we can use template mode to solve these repetitive work, such as when we buy things are generally the choice of goods, payment, such as the steps, the difference is only the selection of the product variety is different, this time we can use template mode. So how does the template pattern need to be implemented, such as

The code is as follows:

public class Test

{

public static void Main (String args[])

{

Goods f=new fruit ();

F.run ();

Goods d=new drink ();

D.run ();

}

}

Class goods

{

void Run ()

{

Getgoods ();

Pay ();

}

void Getgoods ()

{

System.out.println ("get");

}

void Pay ()

{

SYSTEM.OUT.PRINTLN ("pay");

}

}

Class Fruit extends goods

{

void Getgoods ()

{

System.out.println ("fruit");

}

}

Class drink extends Goods

{

void Getgoods ()

{

System.out.println ("Drink");

}

}

Results

This allows us to avoid involving specific algorithms in subclasses, simply by extracting the duplicated content from the algorithm to the parent class, reducing the coupling.

At this point, we can also join a hook mechanism, can be corresponding to some of the unnecessary algorithms to control.

The code is as follows

public class Test

{

public static void Main (String args[])

{

Goods f=new fruit ();

F.run ();

Goods d=new drink ();

D.run ();

}

}

Class goods

{

void Run ()

{

if (Hasgetgoods ())

Getgoods ();

Pay ();

}

void Getgoods ()

{

System.out.println ("get");

}

Boolean hasgetgoods ()

{

return false;

}

void Pay ()

{

SYSTEM.OUT.PRINTLN ("pay");

}

}

Class Fruit extends goods

{

Boolean hasgetgoods ()

{

return true;

}

void Getgoods ()

{

System.out.println ("fruit");

}

}

Class drink extends Goods

{

Boolean hasgetgoods ()

{

return false;

}

void Getgoods ()

{

System.out.println ("Drink");

}

}

Results:

Contact me: [Email protected]

2016-8-3

21:25

Touch Plate mode and hooks

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.