29
loading...
This website collects cookies to deliver better user experience
Objects or entities should be open for extension but closed for modification.
public class Rectangle
{
public double Height { get; set; }
public double Width { get; set; }
}
public class AreaCalculator
{
public double TotalArea(Rectangle[] rectangles)
{
double result = 0;
foreach(Rectangle rectangle in rectangles
result += rectangle.Height * rectangle.Width;
return result;
}
}
public class Circle
{
public double Radius { get; set; }
}
AreaCalculator
class.public class AreaCalculator
{
public double TotalArea(object[] shapes)
{
double result = 0;
foreach(object shape in shapes)
{
if(shape is Rectangle)
{
Rectangle rectangle = (Rectangle)obj;
result += rectangle.Height * rectangle.Width;
}
if(shape is Circle)
{
Circle circle = (Circle)obj;
result += circle.Radius * circle.Radius * Math.PI;
}
}
return result;
}
}
Circle
to our application. Triangle
or a Square
? We would need to add more and more if
statements to our TotalArea
method.Rectangle
and Circle
can derive from the same abstract concept, a Shape
.public abstract class Shape
{
public double CalculateArea();
}
Shape
class in our "Shapes".public class Rectangle: Shape
{
public double Height { get; set; }
public double Width { get; set; }
public double CalculateArea()
{
return Height * Width;
}
}
public class Circle: Shape
{
public double Radius { get; set; }
public double CalculateArea()
{
return Radius * Radius * Math.PI;
}
}
CalculateArea
from our Shape
class, we need to update the AreaCalculator
class.public class AreaCalculator
{
public double TotalArea(Shape[] shapes)
{
double result = 0;
foreach(Shape shape in shapes)
{
result += shape.CalculateArea();
}
return result;
}
}
Triangle
class for example) but closed for modifications, only modifying if any bugs were founds.