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

更新於:05-Dec-2020

470 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.