设计模式之开放封闭原则

定义

1
2
3
开放-封闭原则:是说软件实体(类、模块、函数等等)应该可以扩展,但是不可修改。【ASD】
// 对于扩展是开放的,对于更改是封闭的。在开发过程中面对需求,对程序的改动是通过增加新代码进行的额,而不是更改现有的代码。
// 有点像一国两制,对于大陆来说社会主义是不可改变的,对于香港来说长期在殖民统治进行彻底的变化是不现实的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.List;

// 抽象形状接口
interface Shape {
double area();
}

// 矩形类
class Rectangle implements Shape {
private double width;
private double height;

public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

@Override
public double area() {
return width * height;
}
}

// 圆形类
class Circle implements Shape {
private double radius;

public Circle(double radius) {
this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

// 面积计算器类
class AreaCalculator {
public double calculateArea(List<Shape> shapes) {
double totalArea = 0;
for (Shape shape : shapes) {
totalArea += shape.area();
}
return totalArea;
}
}

// 主类,用于演示
public class Main {
public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();
List<Shape> shapes = List.of(new Rectangle(5, 10), new Circle(7));
double totalArea = calculator.calculateArea(shapes);
System.out.printf("Total area: %.2f%n", totalArea);
}
}