Java Learning notes-design pattern Vii. Template Method pattern

Source: Internet
Author: User

Template Method Pattern (Templatemethod), which defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. The template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.

Structure diagram:

Code:

Algorithm skeleton:

1 Package Cn.happy.design_pattern._07templatemethod;2 3  Public Abstract classAbstractClass {4 5      Public Abstract voidPrimitiveOperation1 ();6      Public Abstract voidPrimitiveOperation2 ();7      Public voidTemplatemethod () {8 PrimitiveOperation1 ();9 PrimitiveOperation2 ();Ten     } One}

Some of the steps of overriding an algorithm skeleton:

1 Package Cn.happy.design_pattern._07templatemethod;2 3  Public classConcreteclassa extends AbstractClass {4 5 @Override6      Public voidPrimitiveOperation1 () {7System. out. println ("Concrete Class A Method 1 implementation");8 9     }Ten  One @Override A      Public voidPrimitiveOperation2 () { -System. out. println ("Concrete Class A Method 2 implementation"); -  the     } -  - } -  Public classConcreteclassb extends AbstractClass { +  - @Override +      Public voidPrimitiveOperation1 () { ASystem. out. println ("Concrete Class B Method 1 Implementation"); at  -     } -  - @Override -      Public voidPrimitiveOperation2 () { -System. out. println ("Concrete Class B Method 2 implementation"); in  -     } to  +}

Test class:

1 Package Cn.happy.design_pattern._07templatemethod;2 3  Public classMmain {4 5      Public Static voidMain (string[] args) {6AbstractClass C =NewConcreteclassa ();7 C.templatemethod ();8c =NewCONCRETECLASSB ();9 C.templatemethod ();Ten  One     } A  -}

Java Learning notes-design pattern Vii. Template Method pattern

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.