开闭原则(OCP)规定,软件实体应该对扩展开发,对修改关闭。简单理解当应用的需求改变时,在不修改原有代码的基础上就可以扩展应用的功能,使其满足新需求。
    优点:。

    1. 提高代码的可重用性
    2. 提高可维护性

    实现方式:
    可以通过接口或者抽象类来为软件实体定义一个相对稳定的抽象层,而将相同的可变逻辑封装到其具体的实现类中
    只要抽象合理,基本可以满足架构的稳定,而其易变的细节可以从具体的实现类中进行扩展,当发生改变时,只需要重新扩展一个实现类即可

    反例:原本我们需要绘制圆形和方形,当我们需要新增一种矩形的时候,需要对原有的代码进行修改,不难想到,当类的功能很复杂的时候,这样的工作量是非常大的。

    1. public static void main(String[] args) {
    2. GraphicEditor editor = new GraphicEditor();
    3. editor.drawShape(new Rectangle()); // 绘制长方形
    4. editor.drawShape(new Circle()); // 绘制圆形
    5. editor.drawShape(new Triangle()); // 绘制三角形
    6. }
    7. // 绘图
    8. static class GraphicEditor{
    9. // 接收基类,根据type,绘制不同的图形
    10. public void drawShape(Shape shape){
    11. if (shape.type == 1){
    12. // 绘制长方形
    13. this.drawRectangle();
    14. }else if (shape.type == 2){
    15. // 绘制圆形
    16. this.drawCircle();
    17. }else {
    18. // 绘制三角形
    19. this.drawTriangle();
    20. }
    21. }
    22. private void drawRectangle(){
    23. System.out.println("绘制长方形");
    24. }
    25. private void drawCircle(){
    26. System.out.println("绘制圆形");
    27. }
    28. private void drawTriangle(){
    29. System.out.println("绘制三角形");
    30. }
    31. }
    32. // 表示形状的基类
    33. static class Shape{
    34. int type;
    35. }
    36. // 长方形
    37. static class Rectangle extends Shape{
    38. Rectangle(){
    39. super.type = 1;
    40. }
    41. }
    42. // 圆形
    43. static class Circle extends Shape{
    44. Circle(){
    45. super.type = 2;
    46. }
    47. }
    48. // 三角形
    49. static class Triangle extends Shape{
    50. Triangle(){
    51. super.type = 3;
    52. }
    53. }

    正例:抽象一个绘图的基类,而具体的实现细节则在子类中完成,当需要扩展新的图形时,只需要实现基类实现对应的方法即可,避免了对原本代码逻辑的修改。

    1. public static void main(String[] args) {
    2. GraphicEditor editor = new GraphicEditor();
    3. editor.drawShape(new Rectangle()); // 绘制长方形
    4. editor.drawShape(new Circle()); // 绘制圆形
    5. editor.drawShape(new Triangle()); // 绘制三角形
    6. }
    7. // 绘图
    8. static class GraphicEditor{
    9. // 接收基类,根据type,绘制不同的图形
    10. public void drawShape(Shape shap){
    11. shap.draw();
    12. }
    13. }
    14. // 表示形状的基类
    15. interface Shape{
    16. // 绘制
    17. void draw();
    18. }
    19. // 长方形
    20. static class Rectangle implements Shape {
    21. @Override
    22. public void draw() {
    23. System.out.println("绘制长方形");
    24. }
    25. }
    26. // 圆形
    27. static class Circle implements Shape{
    28. @Override
    29. public void draw() {
    30. System.out.println("绘制圆形");
    31. }
    32. }
    33. // 三角形
    34. static class Triangle implements Shape{
    35. @Override
    36. public void draw() {
    37. System.out.println("绘制三角形");
    38. }
    39. }