如何用C#实现开闭原则?

王林
发布: 2023-08-26 20:33:11
转载
1448 人浏览过

如何用C#实现开闭原则?

像类、模块和函数这样的软件实体应该对扩展开放,但对修改关闭。

定义 - 开放关闭原则指出代码的设计和编写应该以这样的方式完成:在现有代码中进行最少的更改来添加新功能。设计的方式应该允许添加新功能作为新类,并尽可能保持现有代码不变。

示例

打开关闭之前的代码原理

using System;
using System.Net.Mail;
namespace SolidPrinciples.Open.Closed.Principle.Before{
   public class Rectangle{
      public int Width { get; set; }
      public int Height { get; set; }
   }
   public class CombinedAreaCalculator{
      public double Area (object[] shapes){
         double area = 0;
         foreach (var shape in shapes){
            if(shape is Rectangle){
               Rectangle rectangle = (Rectangle)shape;
               area += rectangle.Width * rectangle.Height;
            }
         }
         return area;
      }
   }
   public class Circle{
      public double Radius { get; set; }
   }
   public class CombinedAreaCalculatorChange{
      public double Area(object[] shapes){
         double area = 0;
         foreach (var shape in shapes){
            if (shape is Rectangle){
               Rectangle rectangle = (Rectangle)shape;
               area += rectangle.Width * rectangle.Height;
            }
            if (shape is Circle){
               Circle circle = (Circle)shape;
               area += (circle.Radius * circle.Radius) * Math.PI;
            }
         }
         return area;
      }
   }
}
登录后复制

OpenClosed原则之后的代码

namespace SolidPrinciples.Open.Closed.Principle.After{
   public abstract class Shape{
      public abstract double Area();
   }
   public class Rectangle: Shape{
      public int Width { get; set; }
      public int Height { get; set; }
      public override double Area(){
         return Width * Height;
      }
   }
   public class Circle : Shape{
      public double Radius { get; set; }
      public override double Area(){
         return Radius * Radius * Math.PI;
      }
   }
   public class CombinedAreaCalculator{
      public double Area (Shape[] shapes){
         double area = 0;
         foreach (var shape in shapes){
            area += shape.Area();
         }
         return area;
      }
   }
}
登录后复制

以上是如何用C#实现开闭原则?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!