如何使用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; } } }
开闭原理后的代码
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; } } }