欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net core系列 65 正反案例介绍SOLID原则

程序员文章站 2024-01-04 09:54:58
一.概述 SOLID五大原则使我们能够管理解决大多数软件设计问题。由Robert C. Martin在20世纪90年代编写了这些原则。这些原则为我们提供了从紧耦合的代码和少量封装转变为适当松耦合和封装业务实际需求的结果方法。使用这些原则,我们可以构建一个具有整洁,可读且易于维护的代码应用程序。 SO ......

一.概述

  solid五大原则使我们能够管理解决大多数软件设计问题。由robert c. martin在20世纪90年代编写了这些原则。这些原则为我们提供了从紧耦合的代码和少量封装转变为适当松耦合和封装业务实际需求的结果方法。使用这些原则,我们可以构建一个具有整洁,可读且易于维护的代码应用程序。

  solid缩写如下:  

    srp  单一责任原则

    ocp 开放/封闭原则

    lsp  里氏替换原则

    isp   接口分离原则

    dip   依赖反转原则

 

  1.单一责任原则srp 

      一个类承担的责任在理想情况下应该是多少个呢?答案是一个。这个责任是围绕一个核心任务构建,不是简化的意思。通过暴露非常有限的责任使这个类与系统的交集更小。

    (1) 演示:违反了单一责任原则,原因是:顾客类中承担了太多无关的责任。  

    /// <summary>
    /// 顾客类所有实现
    /// </summary>
    public class cliente
    {
        public int clienteid { get; set; }
        public string nome { get; set; }
        public string email { get; set; }
        public string cpf { get; set; }
        public datetime datacadastro { get; set; }

        public string adicionarcliente()
        {
            //顾客信息验证
            if (!email.contains("@"))
                return "cliente com e-mail inválido";

            if (cpf.length != 11)
                return "cliente com cpf inválido";

            //保存顾客信息
            using (var cn = new sqlconnection())
            {
                var cmd = new sqlcommand();

                cn.connectionstring = "minhaconnectionstring";
                cmd.connection = cn;
                cmd.commandtype = commandtype.text;
                cmd.commandtext = "insert into cliente (nome, email cpf, datacadastro) values (@nome, @email, @cpf, @datacad))";

                cmd.parameters.addwithvalue("nome", nome);
                cmd.parameters.addwithvalue("email", email);
                cmd.parameters.addwithvalue("cpf", cpf);
                cmd.parameters.addwithvalue("datacad", datacadastro);

                cn.open();
                cmd.executenonquery();
            }

            //发布邮件
            var mail = new mailmessage("empresa@empresa.com", email);
            var client = new smtpclient
            {
                port = 25,
                deliverymethod = smtpdeliverymethod.network,
                usedefaultcredentials = false,
                host = "smtp.google.com"
            };

            mail.subject = "bem vindo.";
            mail.body = "parabéns! você está cadastrado.";
            client.send(mail);

            return "cliente cadastrado com sucesso!";
        }
    }

     (2) 解决方案,使用单一责任原则,每个类只负责自己的业务。

    /// <summary>
    /// 顾客实体
    /// </summary>
    public class cliente
    {
        public int clienteid { get; set; }
        public string nome { get; set; }
        public string email { get; set; }
        public string cpf { get; set; }
        public datetime datacadastro { get; set; }

        /// <summary>
        /// 顾客信息验证
        /// </summary>
        /// <returns></returns>
        public bool isvalid()
        {
            return emailservices.isvalid(email) && cpfservices.isvalid(cpf);
        }
    }

    /// <summary>
    /// 保存顾客信息
    /// </summary>
    public class clienterepository
    {
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="cliente">要保存的顾客实体</param>
        public void adicionarcliente(cliente cliente)
        {
            using (var cn = new sqlconnection())
            {
                var cmd = new sqlcommand();

                cn.connectionstring = "minhaconnectionstring";
                cmd.connection = cn;
                cmd.commandtype = commandtype.text;
                cmd.commandtext = "insert into cliente (nome, email cpf, datacadastro) values (@nome, @email, @cpf, @datacad))";

                cmd.parameters.addwithvalue("nome", cliente.nome);
                cmd.parameters.addwithvalue("email", cliente.email);
                cmd.parameters.addwithvalue("cpf", cliente.cpf);
                cmd.parameters.addwithvalue("datacad", cliente.datacadastro);

                cn.open();
                cmd.executenonquery();
            }
        }
    }

   /// <summary>
    /// cpf服务
    /// </summary>
    public static class cpfservices
    {
        public static bool isvalid(string cpf)
        {
            return cpf.length == 11;
        }
    }

    /// <summary>
    /// 邮件服务
    /// </summary>
    public static class emailservices
    {
        public static bool isvalid(string email)
        {
            return email.contains("@");
        }

        public static void enviar(string de, string para, string assunto, string mensagem)
        {
            var mail = new mailmessage(de, para);
            var client = new smtpclient
            {
                port = 25,
                deliverymethod = smtpdeliverymethod.network,
                usedefaultcredentials = false,
                host = "smtp.google.com"
            };

            mail.subject = assunto;
            mail.body = mensagem;
            client.send(mail);
        }
    }

    /// <summary>
    /// 客户服务,程序调用入口
    /// </summary>
    public class clienteservice
    {
        public string adicionarcliente(cliente cliente)
        {
            //先验证
            if (!cliente.isvalid())
                return "dados inválidos";

            //保存顾客
            var repo = new clienterepository();
            repo.adicionarcliente(cliente);

            //邮件发送
            emailservices.enviar("empresa@empresa.com", cliente.email, "bem vindo", "parabéns está cadastrado");

            return "cliente cadastrado com sucesso";
        }
    }

 

  2. 开放/封闭原则ocp

    类应该是可以可扩展的,可以用作构建其他相关新功能,这叫开放。但在实现相关功能时,不应该修改现有代码(因为已经过单元测试运行正常)这叫封闭。

    (1) 演示:违反了开放/封闭原则,原因是每次增加新形状时,需要改变areacalculator 类的totalarea方法,例如开发后期又增加了圆形形状。

    /// <summary>
    /// 长方形实体
    /// </summary>
    public class rectangle
    {
        public double height { get; set; }
        public double width { get; set; }
    }

    /// <summary>
    /// 圆形
    /// </summary>
    public class circle
    {
        /// <summary>
        /// 半径
        /// </summary>
        public double radius { get; set; }
    }

    /// <summary>
    /// 面积计算 
    /// </summary>
    public class areacalculator
    {
        public double totalarea(object[] arrobjects)
        {
            double area = 0;
            rectangle objrectangle;
            circle objcircle;
            foreach (var obj in arrobjects)
            {
                if (obj is rectangle)
                {
                    objrectangle = (rectangle)obj;
                    area += objrectangle.height * objrectangle.width;
                }
                else
                {
                    objcircle = (circle)obj;
                    area += objcircle.radius * objcircle.radius * math.pi;
                }
            }
            return area;
        }
    }

     (2) 解决方案,使用开放/封闭原则,每次增加新形状时(开放),不需要修改totalarea方法(封闭)

   /// <summary>
    /// 形状抽象类
    /// </summary>
    public abstract class shape
    {
        /// <summary>
        /// 面积计算
        /// </summary>
        /// <returns></returns>
        public abstract double area();
    }

    /// <summary>
    /// 长方形
    /// </summary>
    public class rectangle : shape
    {
        public double height { get; set; }
        public double width { get; set; }
        public override double area()
        {
            return height * width;
        }
    }

    /// <summary>
    /// 圆形
    /// </summary>
    public class circle : shape
    {
        public double radius { get; set; }
        public override double area()
        {
            return radius * radius * math.pi;
        }
    }

    /// <summary>
    /// 面积计算
    /// </summary>
    public class areacalculator
    {
        public double totalarea(shape[] arrshapes)
        {
            double area = 0;
            foreach (var objshape in arrshapes)
            {
                area += objshape.area();
            }
            return area;
        }
    }

  

  3.里氏替换原则lsp

    这里也涉及到了类的继承,也适用于接口。子类可以替换它们的父类。里氏替换原则常见的代码问题是使用虚方法,在父类定义虚方法时,要确保该方法里没有任何私有成员。

    (1) 演示:违反了里氏替换原则, 原因是不能使用readonlysqlfile子类替代sqlfile父类。

    /// <summary>
    /// sql文件类 读取、保存 
    /// </summary>
    public class sqlfile
    {
        public string filepath { get; set; }
        public string filetext { get; set; }
        public virtual string loadtext()
        {
            /* code to read text from sql file */
            return "..";
        }
        public virtual void savetext()
        {
            /* code to save text into sql file */
        }
    }

    /// <summary>
    /// 开发途中增加了sql文件只读类
    /// </summary>
    public class readonlysqlfile : sqlfile
    {
        public override string loadtext()
        {
            /* code to read text from sql file */
            return "..";
        }
        public override void savetext()
        {
            /* throw an exception when app flow tries to do save. */
            throw new ioexception("can't save");
        }
    }


    public class sqlfilemanager
    {
        /// <summary>
        /// 集合中存在两种类:sqlfile和readonlysqlfile
        /// </summary>
        public list<sqlfile> lstsqlfiles { get; set; }

        /// <summary>
        /// 读取
        /// </summary>
        /// <returns></returns>
        public string gettextfromfiles()
        {
            stringbuilder objstrbuilder = new stringbuilder();
            foreach (var objfile in lstsqlfiles)
            {
                objstrbuilder.append(objfile.loadtext());
            }
            return objstrbuilder.tostring();
        }

        /// <summary>
        /// 保存
        /// </summary>
        public void savetextintofiles()
        {
            foreach (var objfile in lstsqlfiles)
            {
                //检查当前对象是readonlysqlfile类,跳过调用savetext()方法  
                if (!(objfile is readonlysqlfile))
                {
                    objfile.savetext();
                }
            }
        }
    }  

     (2) 解决方案,使用里氏替换原则,子类可以完全代替父类

   public interface ireadablesqlfile
    {
        string loadtext();
    }
    public interface iwritablesqlfile
    {
        void savetext();
    }

    public class readonlysqlfile : ireadablesqlfile
    {
        public string filepath { get; set; }
        public string filetext { get; set; }
        public string loadtext()
        {
            /* code to read text from sql file */
            return "";
        }
    }


    public class sqlfile : iwritablesqlfile, ireadablesqlfile
    {
        public string filepath { get; set; }
        public string filetext { get; set; }
        public string loadtext()
        {
            /* code to read text from sql file */
            return "";
        }
        public void savetext()
        {
            /* code to save text into sql file */
        }
    }


    public class sqlfilemanager
    {
        public string gettextfromfiles(list<ireadablesqlfile> alstreadablefiles)
        {
            stringbuilder objstrbuilder = new stringbuilder();
            foreach (var objfile in alstreadablefiles)
            {
                //readonlysqlfile的loadtext实现
                objstrbuilder.append(objfile.loadtext());
            }
            return objstrbuilder.tostring();
        }

        public void savetextintofiles(list<iwritablesqlfile> alstwritablefiles)
        {
            foreach (var objfile in alstwritablefiles)
            {
                //sqlfile的savetext实现
                objfile.savetext();
            }
        }
    }

 

  4.接口分离原则isp

    接口分离原则是解决接口臃肿的问题,建议接口保持最低限度的函数。永远不应该强迫客户端依赖于它们不用的接口。

     (1)  演示:违反了接口分离原则。原因是manager无法处理任务,同时没有人可以将任务分配给manager,因此workontask方法不应该在manager类中。

   /// <summary>
    /// 领导接口
    /// </summary>
    public interface ilead
    {
        //创建任务
        void createsubtask();
        //分配任务
        void assgintask();
        //处理指定任务
        void workontask();
    }

    /// <summary>
    /// 团队领导
    /// </summary>
    public class teamlead : ilead
    {
        public void assgintask()
        {
            //code to assign a task.  
        }
        public void createsubtask()
        {
            //code to create a sub task  
        }
        public void workontask()
        {
            //code to implement perform assigned task.  
        }
    }

    /// <summary>
    /// 管理者
    /// </summary>
    public class manager : ilead
    {
        public void assgintask()
        {
            //code to assign a task.  
        }
        public void createsubtask()
        {
            //code to create a sub task.  
        }
        public void workontask()
        {
            throw new exception("manager can't work on task");
        }
    }

     (2) 解决方案,使用接口分离原则

    /// <summary>
    /// 程序员角色
    /// </summary>
    public interface iprogrammer
    {
        void workontask();
    }

    /// <summary>
    /// 领导角色
    /// </summary>
    public interface ilead
    {
        void assigntask();
        void createsubtask();
    }

    /// <summary>
    /// 程序员:执行任务
    /// </summary>
    public class programmer : iprogrammer
    {
        public void workontask()
        {
            //code to implement to work on the task.  
        }
    }

    /// <summary>
    /// 管理者:可以创建任务、分配任务
    /// </summary>
    public class manager : ilead
    {
        public void assigntask()
        {
            //code to assign a task  
        }
        public void createsubtask()
        {
            //code to create a sub taks from a task.  
        }
    }

    /// <summary>
    /// 团队领域:可以创建任务、分配任务、执行执行
    /// </summary>
    public class teamlead : iprogrammer, ilead
    {
        public void assigntask()
        {
            //code to assign a task  
        }
        public void createsubtask()
        {
            //code to create a sub task from a task.  
        }
        public void workontask()
        {
            //code to implement to work on the task.  
        }
    }

 

  5. 依赖反转原则dip

    依赖反转原则是对程序的解耦。高级模块/类不应依赖于低级模块/类,两者都应该依赖于抽象。意思是:当某个类被外部依赖时,就需要把该类抽象成一个接口。接口如何变成可调用的实例呢?实践中多用依赖注入模式。这个依赖反转原则在ddd中得到了很好的运用实践(参考前三篇)。

    (1) 演示:违反了依赖反转原则。原因是:每当客户想要引入新的logger记录形式时,我们需要通过添加新方法来改变exceptionlogger类。这里错误的体现了:高级类 exceptionlogger直接引用低级类filelogger和dblogger来记录异常。

   /// <summary>
    /// 数据库日志类
    /// </summary>
    public class dblogger
    {
        //写入日志
        public void logmessage(string amessage)
        {
            //code to write message in database.  
        }
    }


    /// <summary>
    /// 文件日志类
    /// </summary>
    public class filelogger
    {
        //写入日志
        public void logmessage(string astacktrace)
        {
            //code to log stack trace into a file.  
        }
    }

    public class exceptionlogger
    {
        public void logintofile(exception aexception)
        {
            filelogger objfilelogger = new filelogger();
            objfilelogger.logmessage(getuserreadablemessage(aexception));
        }

        public void logintodatabase(exception aexception)
        {
            dblogger objdblogger = new dblogger();
            objdblogger.logmessage(getuserreadablemessage(aexception));
        }

        private string getuserreadablemessage(exception ex)
        {
            string strmessage = string.empty;
            //code to convert exception's stack trace and message to user readable format.  
            return strmessage;
        }
    }


    public class dataexporter
    {
        public void exportdatafromfile()
        {
            try
            {
                //code to export data from files to database.  
            }
            catch (ioexception ex)
            {
                new exceptionlogger().logintodatabase(ex);
            }
            catch (exception ex)
            {
                new exceptionlogger().logintofile(ex);
            }
        }
    }

     (2) 解决方案,使用依赖反转原则,这里演示没有用依赖注入。

   public interface ilogger
    {
        void logmessage(string astring);
    }


    /// <summary>
    /// 数据库日志类
    /// </summary>
    public class dblogger : ilogger
    {
        //写入日志
        public void logmessage(string amessage)
        {
            //code to write message in database.  
        }
    }


    /// <summary>
    /// 文件日志类
    /// </summary>
    public class filelogger : ilogger
    {
        //写入日志
        public void logmessage(string astacktrace)
        {
            //code to log stack trace into a file.  
        }
    }


    public class exceptionlogger
    {
        private ilogger _logger;
        public exceptionlogger(ilogger alogger)
        {
            this._logger = alogger;
        }
//可以与这些日志类达到松散耦合 public void logexception(exception aexception) { string strmessage = getuserreadablemessage(aexception); this._logger.logmessage(strmessage); } private string getuserreadablemessage(exception aexception) { string strmessage = string.empty; //code to convert exception's stack trace and message to user readable format. return strmessage; } } public class dataexporter { public void exportdatafromfile() { exceptionlogger _exceptionlogger; try { //code to export data from files to database. } catch (ioexception ex) { _exceptionlogger = new exceptionlogger(new dblogger()); _exceptionlogger.logexception(ex); } catch (exception ex) { _exceptionlogger = new exceptionlogger(new filelogger()); _exceptionlogger.logexception(ex); } } }

 

  参考文献

    solid原则简介

 

上一篇:

下一篇: