如何使用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;
}
}
}热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短