1. 程式人生 > 其它 >設計模式-七大設計原則-開閉原則

設計模式-七大設計原則-開閉原則

一、開閉原則介紹

二、開閉原則引入

1.方式一(違反了開閉原則)

  UML類圖:

  程式碼及解析:這裡所有Shape類的子類為提供方,GraphicEditor類為使用方。當需要增加一個"三角形提供方"的時候,除了要新增一個三角形類,還要在使用方中新增type判斷分支以及drawTriangle方法。這違反了"對修改關閉",也就是違反了開閉原則。

public class Ocp {
    public static void main(String[] args) {
        //使用看看存在的問題
        GraphicEditor graphicEditor = new
GraphicEditor(); graphicEditor.drawShape(new Rectangle()); graphicEditor.drawShape(new Circle()); graphicEditor.drawShape(new Triangle()); } } //這是一個用於繪圖的類 [使用方] class GraphicEditor { //接收Shape物件,然後根據type,來繪製不同的圖形 public void drawShape(Shape s) { if (s.m_type == 1) drawRectangle(s);
else if (s.m_type == 2) drawCircle(s); else if (s.m_type == 3) drawTriangle(s); } //繪製矩形 public void drawRectangle(Shape r) { System.out.println(" 繪製矩形 "); } //繪製圓形 public void drawCircle(Shape r) { System.out.println(" 繪製圓形 "); }
//繪製三角形 public void drawTriangle(Shape r) { System.out.println(" 繪製三角形 "); } } //Shape類,基類 class Shape { int m_type; } class Rectangle extends Shape { Rectangle() { super.m_type = 1; } } class Circle extends Shape { Circle() { super.m_type = 2; } } //新增畫三角形 class Triangle extends Shape { Triangle() { super.m_type = 3; } }

2.方式二(遵守了開閉原則)

  UML類圖:

  程式碼及解析:這裡所有的Shape子類為提供方,GraphicEditor類為使用方。當需要增加一個"其他圖形提供方"的時候,只需要新增一個其他圖形類即可,使用方中無需修改。這遵守了開閉原則。

/**
 * 對擴充套件開放(提供方)
 * 對修改關閉(使用方)
 */
public class Ocp {
    public static void main(String[] args) {
        GraphicEditor graphicEditor = new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
        graphicEditor.drawShape(new Triangle());
        graphicEditor.drawShape(new OtherGraphic());
    }
}

//這是一個用於繪圖的類 [使用方]
class GraphicEditor {
    //接收Shape物件,然後根據type,來繪製不同的圖形
    public void drawShape(Shape s) {
        s.draw();
    }
}

//Shape類,基類
abstract class Shape {

    int m_type;

    public abstract void draw();//抽象方法

}

class Rectangle extends Shape {
    Rectangle() {
        super.m_type = 1;
    }

    @Override
    public void draw() {
        System.out.println("繪製矩形");
    }
}

class Circle extends Shape {
    Circle() {
        super.m_type = 2;
    }

    @Override
    public void draw() {
        System.out.println("繪製圓形");
    }
}

//新增畫三角形
class Triangle extends Shape {
    Triangle() {
        super.m_type = 3;
    }

    @Override
    public void draw() {
        System.out.println("繪製三角形");
    }
}

//新增其他
class OtherGraphic extends Shape {
    OtherGraphic() {
        super.m_type = 4;
    }

    @Override
    public void draw() {
        System.out.println("繪製其他圖形");
    }
}