开闭原则(OCP)规定,软件实体应该对扩展开发,对修改关闭。简单理解当应用的需求改变时,在不修改原有代码的基础上就可以扩展应用的功能,使其满足新需求。
优点:。
- 提高代码的可重用性
- 提高可维护性
实现方式:
可以通过接口或者抽象类来为软件实体定义一个相对稳定的抽象层,而将相同的可变逻辑封装到其具体的实现类中
只要抽象合理,基本可以满足架构的稳定,而其易变的细节可以从具体的实现类中进行扩展,当发生改变时,只需要重新扩展一个实现类即可
反例:原本我们需要绘制圆形和方形,当我们需要新增一种矩形的时候,需要对原有的代码进行修改,不难想到,当类的功能很复杂的时候,这样的工作量是非常大的。
public static void main(String[] args) {GraphicEditor editor = new GraphicEditor();editor.drawShape(new Rectangle()); // 绘制长方形editor.drawShape(new Circle()); // 绘制圆形editor.drawShape(new Triangle()); // 绘制三角形}// 绘图static class GraphicEditor{// 接收基类,根据type,绘制不同的图形public void drawShape(Shape shape){if (shape.type == 1){// 绘制长方形this.drawRectangle();}else if (shape.type == 2){// 绘制圆形this.drawCircle();}else {// 绘制三角形this.drawTriangle();}}private void drawRectangle(){System.out.println("绘制长方形");}private void drawCircle(){System.out.println("绘制圆形");}private void drawTriangle(){System.out.println("绘制三角形");}}// 表示形状的基类static class Shape{int type;}// 长方形static class Rectangle extends Shape{Rectangle(){super.type = 1;}}// 圆形static class Circle extends Shape{Circle(){super.type = 2;}}// 三角形static class Triangle extends Shape{Triangle(){super.type = 3;}}
正例:抽象一个绘图的基类,而具体的实现细节则在子类中完成,当需要扩展新的图形时,只需要实现基类实现对应的方法即可,避免了对原本代码逻辑的修改。
public static void main(String[] args) {GraphicEditor editor = new GraphicEditor();editor.drawShape(new Rectangle()); // 绘制长方形editor.drawShape(new Circle()); // 绘制圆形editor.drawShape(new Triangle()); // 绘制三角形}// 绘图static class GraphicEditor{// 接收基类,根据type,绘制不同的图形public void drawShape(Shape shap){shap.draw();}}// 表示形状的基类interface Shape{// 绘制void draw();}// 长方形static class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("绘制长方形");}}// 圆形static class Circle implements Shape{@Overridepublic void draw() {System.out.println("绘制圆形");}}// 三角形static class Triangle implements Shape{@Overridepublic void draw() {System.out.println("绘制三角形");}}
