C # Design Pattern Series Tutorials-Template method Pattern _c# Tutorial

Source: Internet
Author: User

1. Overview

Defines the skeleton of an algorithm in an operation, and defers the step to a subclass. Template methods enable subclasses to redefine some specific steps of an algorithm without altering the structure of an algorithm.

2. Role in the pattern

2.1 Abstract Class (AbstractClass): The template method is implemented, and the skeleton of the algorithm is defined.

2.2 Concrete Class (Concreteclass): Implements the abstract method in the abstract class, has completed the complete algorithm.

3. Pattern Interpretation

3.1 Template Method Class diagram

3.2 Template Method pattern code implementation

 <summary>///abstract class///</summary> public abstract class AbstractClass {//Some abstract behavior, put into subclasses to implement public
  abstract void PrimitiveOperation1 ();

  public abstract void PrimitiveOperation2 ();
  <summary>///Template method, gives the skeleton of logic, and logic is composed of some corresponding abstract operations, they are deferred to subclasses to implement.
   </summary> public void Templatemethod () {PrimitiveOperation1 ();
   PrimitiveOperation2 ();
  Console.WriteLine ("Done"); }///<summary>///concrete class, implements specific steps in the abstract class///</summary> public class Concreteclassa:abstractclass {/
   The implementation logic in <summary>///and CONCRETECLASSB is different///</summary> public override void PrimitiveOperation1 () {
  Console.WriteLine ("Implement Operation 1 in Concreate class A."); 
  The implementation logic in///<summary>///and CONCRETECLASSB is different///</summary> public override void PrimitiveOperation2 ()
  {Console.WriteLine ("Implement Operation 2 in Concreate class A."); }///<summary>///specific classes that implement specific steps in an abstract class///;/summary> public class Concreteclassb:abstractclass {///<summary>///differs from the implementation logic in Concreteclassa/// t;/summary> public override void PrimitiveOperation1 () {Console.WriteLine ("Implement operation 1 in Concreate C

  Lass B. ");}
   The implementation logic in <summary>///and Concreteclassa is different///</summary> public override void PrimitiveOperation2 () {
  Console.WriteLine ("Implement Operation 2 in Concreate class B.");

 }
 }

3.3 Client Code

 Class program
 {
  static void Main (string[] args)
  {
   //Declaration abstract class
   AbstractClass C;

   Instantiating c
   C = new Concreteclassa () with Concreteclassa;
   C.templatemethod ();

   Instantiating c
   C = new Concreteclassb () with CONCRETECLASSB;
   C.templatemethod ();

   Console.read ();
  }
 

Run results

5. Model Summary

5.1 Advantages

The 5.1.1 Template method pattern removes duplicate code from subclasses by moving the invariant behavior to the superclass.

The 5.1.2 subclass implements some of the details of the algorithm, which is helpful to the extension of the algorithm.

5.1.3 the actions implemented by calling subclasses through a parent class, adding new behavior through subclass extensions, in line with the open-closed principle.

5.2 Disadvantages

5.2.1 Each implementation needs to define a subclass, which causes the number of classes to increase and the design more abstract.

5.3 Applicable Scenarios

5.1 In some classes of algorithms, using the same method, resulting in the duplication of code.

5.2 Control Subclass extensions, subclasses must follow algorithm rules.

6. Mode example: The bubble algorithm is not the integer array, floating point array, date array to achieve sorting.

6.1 Implementation Class diagram

6.2 Implementation Code

 <summary>///Abstract class that defines a bubble-sorted skeleton///</summary> Public abstract class Bubblesorter {private int Operat
  ions = 0;

  protected int length = 0; 
   <summary>///bubble Sort algorithm///</summary>///<returns></returns> protected int dosort () {
   Operations = 0;
   if (length <= 1) {return operations; for (int nexttolast = length-2, nexttolast >= 0; nexttolast--) {for (int index = 0; Index <= nexttol Ast
     index++) {if (Outoforder (index)) {Swap (index);
    } operations++;
  } return operations; ///<summary>///Swap location method for subclass implementation///</summary>///<param name= "index" ></param> prote
  CTED abstract void Swap (int index); <summary>///A comparison method for implementing a subclass///</summary>///<param name= "index" ></param>///<retu
 Rns></returns> protected abstract bool Outoforder (int index); }///<summary>/The bubble algorithm for integral type implementation///</summary> public class Intbubblesorter:bubblesorter {private int[] array = null; <summary>///using bubble algorithm to sort///</summary>///<param name= "TheArray" ></param>///<retur
   ns></returns> public int Sort (int[] thearray) {array = TheArray; Length = array.
   Length;
  Call Bubble Algorithm return Dosort (); ///<summary>///Implementation of the swap operation in the bubbling algorithm///</summary>///<param name= "index" ></param> Protec
   Ted override void Swap (int index) {int temp = Array[index];
   Array[index] = Array[index + 1];
  Array[index + 1] = temp; ///<summary>///Implementation of the comparison operation in the bubbling algorithm///</summary>///<param name= "index" ></param>///&L  t;returns></returns> protected override bool Outoforder (int index) {return (Array[index] > Array[index
  + 1]);
 The bubbling algorithm for the///<summary>///floating-point number type///</summary> public class Floatbubblesorter:bubblesorter{private float[] array = null; <summary>///using bubble algorithm to sort///</summary>///<param name= "TheArray" ></param>///<retur
   ns></returns> public int Sort (float[] thearray) {array = TheArray; Length = array.
   Length;
  Call Bubble Algorithm return Dosort (); ///<summary>///Implementation of the swap operation in the bubbling algorithm///</summary>///<param name= "index" ></param> Protec
   Ted override void Swap (int index) {Float temp = Array[index];
   Array[index] = Array[index + 1];
  Array[index + 1] = temp; ///<summary>///Implementation of the comparison operation in the bubbling algorithm///</summary>///<param name= "index" ></param>///&L  t;returns></returns> protected override bool Outoforder (int index) {return (Array[index] > Array[index
  + 1]);

 }
 }

6.3 Client Invocation

 Class program
 {
  static void Main (string[] args)
  {

   //Sort integer array
   int[] Intarray = new int[]{5, 3, 12, 8, 1 0};
   Bubblesorter.intbubblesorter sorter = new Bubblesorter.intbubblesorter ();
   Sorter. Sort (intarray);
   foreach (int item in Intarray)
   {
    Console.Write (item+ "");
   }

   Console.WriteLine ("");

   Sort float[for floating-point numbers
   ] Floatarray = new float[] {5.0f, 3.0f, 12.0f, 8.0f, 10.0f};
   Bubblesorter.floatbubblesorter floatsorter = new Bubblesorter.floatbubblesorter ();
   Floatsorter.sort (Floatarray);
   foreach (float item in Floatarray)
   {
    Console.Write (item + "");
   }

   Console.read ();
  }
 

Run results

The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.

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.