一、开闭(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("这是其余图形"); } }