C# 设计模式(14)模板方法

模板方法

1.定义通用处理流程,实现通用部分,可变部分留作扩展

代码实现:

模板:

namespace TempleteMethodPattern
{
    public abstract class BaseClient
    {
        public decimal Deposit { get; set; }

        public double Percent { get; set; }

        public decimal Interest { get; set; }

        public void Query(int userId,string password,string userName)
        {
            if (CheckUser(userId, password))
            {
                GetDeposit();
                GetPercent();
                GetInterest();
                DisplayToClient(userName);
            }
        }

        private bool CheckUser(int userId,string password)
        {
            return true;
        }

        private void GetDeposit()
        {
            Random random = new Random();
            Deposit = random.Next(10000, 1000000);
        }

        protected abstract void GetPercent();

        private void GetInterest()
        {
            Interest = Deposit * (decimal)Percent;
        }

        protected virtual void DisplayToClient(string name)
        {
            Console.WriteLine($"尊敬的{name}客户,您的利率:{Percent}%,利息:{Interest}");
        }
    }
}

客户类:

    public class NormalClient : BaseClient
    {
        protected override void GetPercent()
        {
            Percent = 0.03;
        }
    }
    public class VipClient : BaseClient
    {
        protected override void DisplayToClient(string name)
        {
            Console.WriteLine($"尊贵{name}客户,您的利率:{Percent}%,利息:{Interest}"+Environment.NewLine+ "理财有风险,入行需谨慎!");
        }

        protected override void GetPercent()
        {
            Percent = 0.05;
        }
    }

代码调用:

    class Program
    {
        static void Main(string[] args)
        {
            BaseClient normal = new NormalClient();
            normal.Query(02,"123","Bob");

            BaseClient vipClient = new VipClient();
            vipClient.Query(01, "456", "Alex");
        }
    }

结果:

原文地址:https://www.cnblogs.com/YourDirection/p/14094267.html