像類別、模組和函數這樣的軟體實體應該對擴充功能開放,但對修改關閉。
定義 - 開放關閉原則指出程式碼的設計和編寫應該以這樣的方式完成:在現有程式碼中進行最少的變更來新增功能。設計的方式應該允許添加新功能作為新類別,並儘可能保持現有程式碼不變。
打開關閉之前的程式碼原理
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中文網其他相關文章!