如何使用 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; } } }
广告