首页 > 其他分享 >CSharp: Chain of Responsibility Pattern in donet core 3

CSharp: Chain of Responsibility Pattern in donet core 3

时间:2022-10-12 06:33:05浏览次数:45  
标签:donet Chain core Message public nextReceiver msg message HandleMessage

 

 /// <summary>
    ///责任链模式 Chain of Responsibility Pattern  亦称: 职责链模式、命令链、CoR、Chain of Command、Chain of Responsibility
    /// geovindu,Geovin Du edit
    /// </summary>
    public enum MessagePriority
    {
        /// <summary>
        /// 正常
        /// </summary>
        [Description("正常")]
        Normal = 1,
        /// <summary>
        /// 高
        /// </summary>
        [Description("高")]
        High =2
    }


    public static class geovindu
    {

        /// <summary>
        /// 扩展方法,获得枚举的Description
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
        /// <returns>枚举的Description</returns>
        public static string GetDescription(this Enum value, Boolean nameInstead = true)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name == null)
            {
                return null;
            }

            FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

            if (attribute == null && nameInstead == true)
            {
                return name;
            }
            return attribute?.Description;
        }
    }


    /// <summary>
    /// Message class
    /// </summary>
    public class Message
    {
        public string Text { get; set; }
        public MessagePriority Priority;
        /// <summary>
        /// 
        /// </summary>
        public string Ms { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="priority"></param>
        public Message(string msg, MessagePriority priority)
        {
            this.Text = msg;
            this.Priority = priority;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="ms"></param>
        public Message(string msg, string ms)
        {
            this.Text = msg;
            this.Ms = ms;
        }
    }
    /// <summary>
    /// Abstract class -Receiver
    /// The abstract class is chosen to share 
    /// the common codes across derived classes.
    /// </summary>
    abstract class Receiver
    {
        protected Receiver nextReceiver;
        //To set the next handler in the chain.
        public void NextReceiver(Receiver nextReceiver)
        {
            this.nextReceiver = nextReceiver;
        }
        public abstract void HandleMessage(Message message);
    }
    /// <summary>
    /// Fax Error Handler class
    /// </summary>
    class FaxErrorHandler : Receiver
    {
        bool messagePassedToNextHandler = false;
        public override void HandleMessage(Message message)
        {
            //Start processing if the error message contains "fax"
            if (message.Text.Contains("fax"))
            {
                Console.WriteLine($" 已处理传真错误处理程序 {message.Ms}  优先排队 : {message.Text}");
                //Do not leave now, if the error message contains email too.
                if (nextReceiver != null && message.Text.Contains("email"))
                {
                    Console.WriteLine("我已经修复了传真侧的缺陷。现在电子邮件团队需要在这个修复的顶部工作");
                    nextReceiver.HandleMessage(message);
                    //We'll not pass the message repeatedly to next handler.
                    messagePassedToNextHandler = true;
                }
            }
            if (nextReceiver != null && messagePassedToNextHandler != true)
            {
                nextReceiver.HandleMessage(message);
            }
        }
    }
    /// <summary>
    /// Email Error Handler class
    /// </summary>
    class EmailErrorHandler : Receiver
    {
        bool messagePassedToNextHandler = false;
        public override void HandleMessage(Message message)
        {
            //Start processing if the error message contains "email"
            if (message.Text.Contains("email"))
            {
                Console.WriteLine($"处理电子邮件错误处理程序{message.Ms}  优先排队: {message.Text}");
                //Do not leave now, if the error message contains "fax" too.
                if (nextReceiver != null && message.Text.Contains("fax"))
                {
                    Console.WriteLine("电子邮件侧缺陷修复。现在传真组需要交叉验证这个修复");
                    //Keeping the following code here.
                    //It can be useful if you place this handler before fax error handler
                    nextReceiver.HandleMessage(message);
                    //We'll not pass the message repeatedly to the next handler.
                    messagePassedToNextHandler = true;
                }
            }
            if (nextReceiver != null && messagePassedToNextHandler != true)
            {
                nextReceiver.HandleMessage(message);
            }
        }
    }
    /// <summary>
    /// UnknownErrorHandler class
    /// </summary>
    class UnknownErrorHandler : Receiver
    {
        public override void HandleMessage(Message message)
        {
            if (!(message.Text.Contains("fax") || message.Text.Contains("email")))
            {
                Console.WriteLine("未知错误发生。立即咨询专家");
            }
            else if (nextReceiver != null)
            {
                nextReceiver.HandleMessage(message);
            }
        }
    }

  

调用:

 //责任链模式 
            Console.WriteLine("***责任链模式 Chain of Responsibility Pattern Demo***\n");

            //Different handlers
            Receiver emailHandler = new EmailErrorHandler();
            Receiver faxHandler = new FaxErrorHandler();
            Receiver unknownHandler = new UnknownErrorHandler();

            faxHandler.NextReceiver(emailHandler);
            emailHandler.NextReceiver(unknownHandler);
            string du=geovindu.GetDescription(MessagePriority.Normal, true);
            string geovin=geovindu.GetDescription(MessagePriority.High, true);
            Message msg = new Message("fax.", du); //MessagePriority.Normal
            faxHandler.HandleMessage(msg);
            msg = new Message("email邮件没有到达目的地.", geovin);
            faxHandler.HandleMessage(msg);
            msg = new Message("email在电子邮件中,抄送字段总是禁用的.", du);
            faxHandler.HandleMessage(msg);
            msg = new Message("fax传真没有到达目的地", geovin);
            faxHandler.HandleMessage(msg);
            msg = new Message("无法登录系统。.", geovin);
            faxHandler.HandleMessage(msg);
            msg = new Message("fax传真和电子邮件都不能用.", geovin);
            faxHandler.HandleMessage(msg);
            Console.ReadKey();

  

输出:

***责任链模式 Chain of Responsibility Pattern Demo***

 已处理传真错误处理程序 正常  优先排队 : fax.
处理电子邮件错误处理程序高  优先排队: email邮件没有到达目的地.
处理电子邮件错误处理程序正常  优先排队: email在电子邮件中,抄送字段总是禁用的.
 已处理传真错误处理程序 高  优先排队 : fax传真没有到达目的地
未知错误发生。立即咨询专家
 已处理传真错误处理程序 高  优先排队 : fax传真和电子邮件都不能用.

  

 

标签:donet,Chain,core,Message,public,nextReceiver,msg,message,HandleMessage
From: https://www.cnblogs.com/geovindu/p/16783206.html

相关文章

  • 使用CoreDNS自建dns
    前言公司有些内网服务需要使用域名访问,安装bind比较麻烦,故使用coredns实现域名服务。IP说明192.168.0.41安装dns,作为dns服务器192.168.0.20测试服务器......
  • 开箱即用~基于.NET Core的统一应用逻辑分层框架设计
    目前公司系统多个应用分层结构各不相同,给运维和未来的开发带来了巨大的成本,分层架构看似很简单,但保证整个研发中心都使用统一的分层架构就不容易了。那么如何保证整个研......
  • DataCore PlgIn for vCenter 3.0 SETTINGs
    第1章 VMwarevSphere3.0Plug-In只需要4步骤,可以在vCenterClient配置一颗存储,可具备高可用性,Multipath-RoundRobin,HighCaching...etc是不是很有趣。1.1 概述VMware......
  • NETCORE中如何操作Appsettings.json 文件
    对于很多初学NETCORE的同学来说,怎么从appsettings.json文件中获取各种类型数据,一直没搞明白。今天我们就对它的几种数据格式的读取做个说明。appsettings.json 是我们......
  • Bitcoin-NG: A Scalable Blockchain Protocol
    Motivation由于比特币平均10分钟出一个块,每个块大小限制在1MB,所以每秒只能记录3~4个交易,导致比特币系统存在着的吞吐量低下和高延迟的问题。本文的主要目的就是通过提......
  • AspNetCore中 使用 Grpc 简单Demo
    为什么要用Grpc跨语言进行,调用服务,获取跨服务器调用等目前我的需要使用我的抓取端是go写的查询端用Net6写的导致很多时候我需要把一些临时数据写入到Redis在两......
  • Portability Analyzer (VS framework 升级到.netcore 前的分析工具,看是否可以升级)使用
    PortabilityAnalyzer(VSframework升级到.netcore前的分析工具,看是否可以升级)使用汇总之前的.NETFramework项目准备迁移到ASP.NETCore,考虑到两个平台对一些API还无法......
  • 注意使用 ImageSharp 或其关联套件 NPOI、PdfSharpCore、ABP 等,现在要收费了
    注意是否使用ImageSharp套件,从2022-7-15开始要收费了,将影响许多工具,如使用NPOI、PdfSharpCore、ABP的用户也要收费。免费使用条件:您正在将作品用于在开源或可用......
  • CSharp: State Pattern in donet core 3
     ///<summary>///状态模式StatePattern///geovindu,GeovinDuedit///</summary>interfaceIPossibleStates{//Userscan......
  • rustup toolchains
    默认的toolchain是stable-x86_64-pc-windows-msvc也可以使用stable-x86_64-pc-windows-gnugnu结尾的需要mingw32默认的需要vsc++buildtoolrustupinstall<toolchai......