写出这个案例开闭原则前代码
时间: 2024-01-22 18:03:05 浏览: 85
开闭原则要求软件实体对扩展开放,对修改关闭。在这个案例中,我们可以使用简单的方式来违反开闭原则,然后再进行改进。
以下是违反开闭原则的前代码:
```csharp
// 定义形状类
public class Shape
{
public string Type { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public double Radius { get; set; }
public double Area()
{
double area = 0;
if (Type == "Rectangle")
{
area = Width * Height;
}
else if (Type == "Circle")
{
area = Math.PI * Radius * Radius;
}
return area;
}
}
// 使用示例
var rectangle = new Shape { Type = "Rectangle", Width = 5, Height = 10 };
var circle = new Shape { Type = "Circle", Radius = 3 };
double totalArea = rectangle.Area() + circle.Area();
Console.WriteLine($"Total area: {totalArea}");
```
在上述代码中,我们定义了一个 `Shape` 类,它包含了表示形状类型的属性 `Type`,以及各个形状的属性。然后在 `Area` 方法中,根据形状的类型进行不同的计算。
这种实现方式违反了开闭原则,因为当我们需要添加新的形状时,需要修改 `Area` 方法的代码来添加新的判断逻辑。
改进后的代码已经在前面提供过了。通过使用抽象基类和多态的方式,将具体的形状类和计算逻辑分离开来,实现了对扩展开放、对修改关闭的设计。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)