zoukankan      html  css  js  c++  java
  • 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");
            }
        }

    结果:

  • 相关阅读:
    Liunx服务器部署MySQL
    TCP/IP协议与Http、RPC和Socket
    InfluxDB简介
    nodeJS中的包
    什么是Solr,它能为我们解决什么问题,怎么用?
    tp基础补充
    用户流程
    已有模板与tp框架的结合 (前台)
    tp模板基础
    Smarty小结提纲
  • 原文地址:https://www.cnblogs.com/YourDirection/p/14094267.html
Copyright © 2011-2022 走看看