Notes-Liar design mode-10 Template Method mode

Source: Internet
Author: User

When we are going to complete a process or a series of steps that are consistent at a certain level of detail, but the implementation of individual steps at a more detailed level may not be the same, we usually consider using a template method pattern to handle it.

The template method pattern, which defines the skeleton of an algorithm in an operation, 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.

The template method pattern is a great way to provide a good code reuse platform. These behaviors are moved to a single place through the template method pattern, which helps the subclass to get rid of the entanglement of repeated invariant behavior.

code example:

 abstract  class   AbstractClass { public  abstract void   Operation1 ();  public  abstract  void   Operation2 ();  public  void   Templatemethod () {Operation1 ();            Operation2 (); Console.WriteLine (   this is templatemethod.          ); }    }
 class   Aclass:abstractclass {public  void   Operation1 () {Console.WriteLine (  "  concrete Class A Method 1 implementation  "  );  public  override  void   Operation2 () {Console.WriteLine (  "  concrete Class A Method 2 implementation  "  ); }    }
    class Bclass:abstractclass    {        publicoverridevoid  Operation1 ()        {            Console.WriteLine ( " Concrete Class B Method 1 Implementation " );        }          Public Override void Operation2 ()        {            Console.WriteLine (" Concrete Class B Method 2 implementation ");        }    }

Test Call:

            abstractclass ac;             New AClass ();            Ac. Templatemethod ();            Console.WriteLine (Environment.NewLine);             New Bclass ();            Ac. Templatemethod ();

Notes-Liar design mode-10 Template Method mode

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.