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

開閉原則(Open Closed Principle)

基本介紹

  • 開閉原則是編程中最基礎、最重要的設計原則
  • 一個軟件實體如類,模塊和函數應該對擴展開放(對提供方),對修改關閉(對使用方)。用抽象構建框架,用實現展示細節。
  • 當軟件需要變化時,儘量通過擴展軟件實體的行爲來實現變化,而不是通過修改已有代碼來實現變化。
  • 編程中遵循其他原則,以及使用設計模式的目的就是遵循開閉原則。

示例

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

該方式優缺點:

  • 優點比較好理解,簡單易操作
  • 缺點是違反了設計模式的ocp原則,即對擴展開放(提供方),對修改關閉(使用方)

改進思路:

1、Shape類改爲抽象類,提供一個抽象的draw方法,子類繼承Shape實現draw方法即可滿足ocp原則

public class Ocp {
    public static void main(String[] args) {
        GraphicEditor graphicEditor=new GraphicEditor();
        graphicEditor.drawShape(new Rectangle());
        graphicEditor.drawShape(new Circle());
    }
}

//這是一個用於繪圖的類
class GraphicEditor{
    public void drawShape(Shape s){
        s.draw();
    }
}

//Shape類,基類
abstract class Shape{
    int m_type;
    public abstract void draw();
}

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

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

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

    @Override
    public void draw() {
        System.out.println("繪製圓形");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章