# O 代表着开闭原则

### 开闭原则

SOLID 中的 ‘O’ 指的是开闭原则。开闭原则如是说：

### 一个开闭原则的例子

Rectangle.java

``public class Rectangle {     private double length;     private double height;     // getters/setters ...  }``

AreaManager.java

``public class AreaManager {     public double calculateArea(ArrayList<Rectangle>... shapes) {         double area = 0;         for (Rectangle rect : shapes) {             area += (rect.getLength() * rect.getHeight());         }         return area;     } }``

`AreaManager` 类一直都把它的工作完成得很好，直到下周我们有一个新的作物的类型出现 – 一个圆形：

Circle.java

``public class Circle {     private double radius;     // getters/setters ...  }``

AreaManager

``public class AreaManager {     public double calculateArea(ArrayList<Object>... shapes) {         double area = 0;         for (Object shape : shapes) {             if (shape instanceof Rectangle) {                 Rectangle rect = (Rectangle)shape;                 area += (rect.getLength() * rect.getHeight());             } else if (shape instanceof Circle) {                 Circle circle = (Circle)shape;                 area += (circle.getRadius() * cirlce.getRadius() * Math.PI;             } else {                 throw new RuntimeException("Shape not supported");             }         }         return area;     } }``

### 采用继承实现开闭原则

Shape.java

``public interface Shape {     double getArea(); }``

Rectangle.java

``public class Rectangle implements Shape {     private double length;     private double height;     // getters/setters ...       @Override     public double getArea() {         return (length * height);     } }``

Circle.java

``public class Circle implements Shape {     private double radius;     // getters/setters ...       @Override     public double getArea() {         return (radius * radius * Math.PI);     } }``

``public class AreaManager {     public double calculateArea(ArrayList<Shape> shapes) {         double area = 0;         for (Shape shape : shapes) {             area += shape.getArea();         }         return area;     } }``

### 结论

1. 从技术上说，开闭原则有两个变种。开闭原则是 Bertrand Meyer 创建的，它的一个变种是 Meyer 的开闭原则。另一个变种是 Polymorphic 的开闭原则。这两个原则都使用继承作为解决方案。这里，我引用 Robert C. Martin 的多态解释