[Handwritten Source-Design Mode 14]-Template Method Mode-Based on Bank System Deposits

1: Theme Disassembly

1 Basic Introduction

(2) Knowledge synchronization

(3) Bank system deposit simulation

(4) Advantages and disadvantages of template method mode

(4) Scenarios applicable

MVC Framework Use

Knowledge Expansion

2: Basic Introduction

Template method mode: simple, powerful, omnipresent, necessary for frame building.

Template method: Define generic processing flow; implement generic part; leave variable part as extension point.

Framework: define business processes; implement common parts; leave variable parts as extension points.

Template method pattern, a template that openly defines the method to execute it in an abstract class. Its subclasses can override the method implementation as needed, but the calls will be made as defined in the abstract class.

Simply put, it defines the algorithm skeleton of an operation and delays some steps to a subclass so that the subclass can redefine some steps of the algorithm without changing the structure of an algorithm.

3: Bank system deposit simulation

This simulated scenario allows users to deposit money in the banking system.

(1) Base class of bank deposit

public abstract class BaseClient
{
    /// <summary>
    ///login query function
    /// </summary>
    /// <param name="id"></param>
    /// <param name="name"></param>
    /// <param name="password"></param>
    public void Query(int id, string name, string password)
    {
        if (this.CheckUser(id, password))
        {
            double balance = this.QueryBalance(id);
            double interest = this.CalculateInterest(balance);
            this.Show(name, balance, interest);
        }
        else
        {
            Console.WriteLine("Account password error");
        }
    }

    /// <summary>
    ///User Detection
    /// </summary>
    /// <param name="id"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public bool CheckUser(int id, string password)
    {
        return DateTime.Now < DateTime.Now.AddDays(1);
    }


    /// <summary>
    ///Query balance
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public double QueryBalance(int id)
    {
        return new Random().Next(10000, 1000000);
    }


    /// <summary>
    ///Get interest rate, calculate interest
    /// </summary>
    /// <param name="balance"></param>
    /// <returns></returns>
    public abstract double CalculateInterest(double balance);


    /// <summary>
    ///Show balance and interest       
    /// </summary>
    /// <param name="name"></param>
    /// <param name="balance"></param>
    /// <param name="interest"></param>
    public virtual void Show(string name, double balance, double interest)
    {
        Console.WriteLine("Honorific{0}Customer, your account balance is:{1},Interest is{2}",
            name, balance, interest);
    }
}

(2) Current users need to rewrite the method of calculating interest when saving money.

    public class ClientCurrent: BaseClient
    { 
        public override double CalculateInterest(double balance)
        {
            return balance * 0.03;
        } 
    }

(3) Periodic users exist because the calculated interest is different

    public class ClientRegular : BaseClient
    { 
        public override double CalculateInterest(double balance)
        {
            return balance * 0.05;
        }
    }

(4) VIP users may not only have different interests, but also different services.

    public class ClientVip : BaseClient
    { 
        public override double CalculateInterest(double balance)
        {
            return balance * 0.07;
        }
        public override void Show(string name, double balance, double interest)
        {
            Console.WriteLine("Noble{0}Customer, your account balance is:{1},Interest is{2}",
                name, balance, interest);
            Console.WriteLine("Financial management is risky and prudent");
        }
    }

Three user access calls

Console.WriteLine("****************ClientCurrent****************");
BaseClient current = new ClientCurrent();
current.Query(234, "current", "123");
Console.WriteLine("****************ClientCurrent****************");
BaseClient regular = new ClientRegular();
regular.Query(345, "regular", "456");
Console.WriteLine("****************ClientVip****************");
BaseClient vip = new ClientVip();
vip.Query(345, "VIP", "789");

Analysis: There are three methods in BaseClient in the user base class.

Common methods: Log on, Check, Balance Query. These three methods are completely universal, so they are implemented in the base class and can be used directly by subclasses.

Abstract method: Calculate interest. Because the calculation rules of interest are different for current user, periodic user and VIP user, it is defined as abstract method in the base class and can be overridden for unnecessary requirements after subclass inheritance.

Virtual method: Display balance and interest. Since most users display the same method, only a small number of special users need to be personalized. This is defined as a virtual method in the base class. Subclasses can be inherited and used directly. If personalized customization is required, rewrite only as required.

4: Advantages and disadvantages of the template approach pattern

1: Advantages

(1) Formal algorithm

Template method patterns formally define an algorithm in the parent class, while subclasses implement detailed processing without changing the order of steps in the algorithm.

(2) Code reuse

The template method pattern is a code reuse technique that extracts common behavior and places it in the parent class to implement different behaviors through subclasses.

3. Implement reverse control

The template method pattern implements a reverse control structure that determines whether a particular step is executed by a hook method in which the subclass overrides the parent class.

(4) It is convenient to add subclasses

The template method pattern can override the basic methods of the parent class through subclasses, which can provide different implementations of the basic methods. It is convenient to replace and add new subclasses.

2: Disadvantages

1. Large number of subclasses

Template method patterns need to provide a subclass for different implementations of each base method. Too many base methods with mutable parents will result in an increase in the number of classes, a larger system, and a more abstract design.

5: Scenarios

(1) Multiple subclasses have common methods and the logic is basically the same.

(2) Important and complex algorithms, the core algorithms can be designed as template methods, and the peripheral detailed functions are implemented by each subclass.

(3) When refactoring, the template method is a commonly used method that extracts the same code into a parent class and then constrains its behavior through a constructor.

6:MVC Framework Usage

 

As shown in the figure above, the template method mode used in the MVC control provides the implementation of the mode, and colleagues have reserved extension points that users can customize.

7: Knowledge Expansion

1: Abstract Method - Execution Result?

public abstract class ParentClass
{ 
    public abstract void Show();
}
public class ChildClass : ParentClass
{ 
    public override void Show()
    {
        Console.WriteLine("This is ChildClass");
    }
}
ParentClass abstractTest1 = new ChildClass();
abstractTest1.Show();
ChildClass abstractTest2 = new ChildClass();
abstractTest2.Show();

Analysis: Abstract classes cannot be instantiated directly or include implementations. Subclasses inherit and implement them, so they all call subclass methods.

2: Common method - Execution result?

public class NewTest
{        
    public void Show()
    {
        Console.WriteLine("This is NewTest");
    }
}
public class NewTestChild : NewTest
{
    public new void Show()
    {
        Console.WriteLine("This is NewTestChild");
    }
}
NewTest newTest1 = new NewTest();
newTest1.Show();
NewTest newTest2 = new NewTestChild();               
newTest2.Show();

Analysis: Normal method calls, compile-time decisions, left decisions. So they are all the parent of calls. Note that when a parent method is narcissistically hidden, new will hide if it doesn't make any difference.

3: Virtual Method - Execution Result?

public class VirtualTest
{
    public virtual void Show()
    {
        Console.WriteLine("This is VirtualTest");
    }
}
public class VirtualTestChild : VirtualTest
{
    public override void Show()
    {
        Console.WriteLine("This is VirtualTestChild");
    }
}
VirtualTest virtualTest1 = new VirtualTest();
VirtualTest virtualTest2 = new VirtualTestChild();
VirtualTestChild virtualTest3 = new VirtualTestChild();
virtualTest1.Show();
virtualTest2.Show();
virtualTest3.Show();

Analysis: Calls to abstract/virtual methods, runtime-determined, right-determined.

A virtual method must contain an implementation, but it can be overridden.

Keywords: C# Design Pattern architecture

Added by deesse on Fri, 17 Sep 2021 12:31:42 +0300