一、開閉(ocp)原則時編程中最基礎、最重要的設計原則
二、一個軟件實體如類、木塊和函數應該對擴展開放,對修改關閉。用抽象構建框架,用實現擴展細節。即對提供方開放,對使用方關閉。
三、當軟件須要變化時,儘可能經過擴展軟件實體的行爲類實現變化,而不是經過修改已有代碼來實現變化
四、編程中遵循其餘原則,以及使用設計模式的目的就是遵循開閉原則。編程
public class Ocp { public static void main(String[] args) { // 使用,看看存在的問題 GraphicEditor graphicEditor = new GraphicEditor(); graphicEditor.drawCircle(new Shape()); graphicEditor.drawRectangle(new Shape()); graphicEditor.drawOther(new Shape()); } } //這是一個用於繪圖的類 class GraphicEditor { 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) { // 需在使用方添加(else if)代碼快 drawOther(s); } } public void drawRectangle(Shape s) { System.out.println("這是矩形"); } public void drawCircle(Shape s) { System.out.println("這是圓形"); } // 需在使用方添加新的方法 public void drawOther(Shape s) { System.out.println("這是其餘圖形"); } } class Shape { int m_type; } class Rectangle extends Shape { Rectangle() { super.m_type = 1; } } class Circle extends Shape { Circle() { super.m_type = 2; } } class Other extends Shape { Other() { super.m_type = 3; } }
一、代碼簡單易懂,思路清晰。
二、但違反了設計模式的ocp原則,即對擴展開放,對修改關閉。即當咱們給類增長新功能的時候,儘可能不修改代碼,或者儘量少修改代碼。
三、每增長一個功能都要需在使用方添加(else if)代碼快,過多的(else if)會使代碼過於臃腫,運行效率不高。設計模式
建立一個Shape類,並提供一個抽象的draw()方法,讓子類實現該方法。每當增長一個圖形種類時,讓該圖形種類繼承Shape類,並實現draw()方法。這樣,使用方只需編寫一個drawShape方法,傳入一個圖形類的對象,便可使用其相應的繪圖方法。只須要修改提供方的代碼,不須要修改使用方的代碼,遵循ocp原則框架
public class Ocp { public static void main(String[] args) { // 遵循ocp原則 GraphicEditor graphicEditor = new GraphicEditor(); graphicEditor.drawShape(new Rectangle()); graphicEditor.drawShape(new Circle()); graphicEditor.drawShape(new Other()); } } //這是一個用於繪圖的類,[使用方] class GraphicEditor { // 接收Shape對象,調用其對應的draw方法 public void drawShape(Shape s) { s.draw(); } } //Shape類,基類 abstract class Shape { public 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 Other extends Shape { Other() { super.m_type = 3; } @Override public void draw() { System.out.println("這是其餘圖形"); } }