java设计模式学习笔记--开闭原则

时间:2023-03-09 16:06:12
java设计模式学习笔记--开闭原则

基本介绍

1、开闭(ocp)原则时编程中最基础、最重要的设计原则

2、一个软件实体如类、木块和函数应该对扩展开放,对修改关闭。用抽象构建框架,用实现扩展细节。即对提供方开放,对使用方关闭

3、当软件需要变化时,尽量通过扩展软件实体的行为类实现变化,而不是通过修改已有代码来实现变化

4、编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则

先来一段代码展示

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;
}
}

分析这段代码中存在的问题

1、代码简单易懂,思路清晰。

2、但违反了设计模式的ocp原则,即对扩展开放,对修改关闭。即当我们给类增加新功能的时候,尽量不修改代码,或者尽可能少修改代码。

3、每增加一个功能都要需在使用方添加(else if)代码快,过多的(else if)会使代码过于臃肿,运行效率不高。

改进思路

创建一个Shape类,并提供一个抽象的draw()方法,让子类实现该方法。每当增加一个图形种类时,让该图形种类继承Shape类,并实现draw()方法。这样,使用方只需编写一个drawShape方法,传入一个图形类的对象,即可使用其相应的绘图方法。只需要修改提供方的代码,不需要修改使用方的代码,遵循ocp原则

使用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("这是其他图形");
}
}