Home  >  Article  >  Backend Development  >  How to implement the open-close principle with C#?

How to implement the open-close principle with C#?

王林
王林forward
2023-08-26 20:33:111423browse

How to implement the open-close principle with C#?

Software entities like classes, modules, and functions should be open for extension but closed for modification.

Definition - The open-closed principle states that the design and writing of code should be done in such a way that minimal changes are made to existing code to add new functionality. The design should be done in a way that allows new functionality to be added as new classes, while keeping existing code unchanged as much as possible.

Example

Code principle before opening and closing

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;
      }
   }
}

Code after OpenClosed principle

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;
      }
   }
}

The above is the detailed content of How to implement the open-close principle with C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete