1.概述
- 开闭原则(Open Closed Principle)是编程中最基础、最重要的设计原则
- 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节。
- 当软件需要变化时,尽量 通过扩展软件实体的行为来实现变化,而 不是通过修改已有的代码来实现变化。
- 编程中遵循其它原则,以及使用设计模式的目的就是遵循开闭原则
2.案例
2.1.描述
2.2.代码
//绘制图形
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)
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;
}
}
测试
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());
}
}
2.3.分析
当我们给类增加新功能的时候,对于使用方来说尽量不修改代码,或者尽可能少修改代码。比如我们这时要新增加一个图形种类 三角形,我们需要继承shape,而且还需要在绘制图形的类中添加新的方法,修改的地方比较多。
2.4改善
把创建Shape类做成抽象类,并提供一个抽象的draw方法,让子类去实现即可,这样我们有新的图形种类时,只需要让新的图形类继承Shape,并实现draw方法即可,使用方的代码就不需要修改-> 满足了开闭原则
class GraphicEditor {
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() {
// TODO Auto-generated method stub
System.out.println("绘制矩形 ");
}
}
class Circle extends Shape {
Circle() {
super.m_type = 2;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println(" 绘制圆形 ");
}
}
//新增,不需要改变使用方的代码
class Triangle extends Shape {
Triangle() {
super.m_type = 3;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("绘制三角形 ");
}
}
测试
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());
}
}