对拓展开放、对修改关闭
有两种理解
- 模块应该在尽量不修改代码的前提下进行拓展
- 提供方的变动不会引起使用方的修改
这就指导我们用抽象来构建框架,用实现拓展细节
上一段代码,根据图形代码画图形
class Shape {
int type;
}
/**
* 矩形
*/
class Rectangle extends Shape {
Rectangle() {
this.type = 1;
}
}
/**
* 这是绘制图形的类
*/
class GraphicEditor {
public void drawShape(Shape shape) {
if (shape.type == 1) {
System.out.println(" 绘制矩形");
}
}
}
思考一下,现在要新增画圆形的方法,代码如下
/**
* 新增矩形类圆形
*/
class Circle extends Shape {
Circle() {
this.type = 2;
}
}
/**
* 修改绘制图形的类
*/
class GraphicEditor {
public void drawShape(Shape shape) {
if (shape.type == 1) {
System.out.println(" 绘制矩形");
}
if (shape.type == 2) {
System.out.println(" 绘制圆形");
}
}
}
看到没,上面的代码拓展了圆形类,使用方GraphicEditor也得跟着改,违背了开闭原则,修改后如下
/**
* 修改为抽象类
*/
abstract class Shape {
int type;
abstract void draw();
}
/**
* 矩形
*/
class Rectangle extends Shape {
Rectangle() {
this.type = 1;
}
@Override
void draw() {
System.out.println(" 绘制矩形");
}
}
/**
* 绘制图形的类
*/
class GraphicEditor {
public void drawShape(Shape shape) {
shape.draw();
}
}
看到没,现在想画圆形,只需新增一个圆形类,使用者GraphicEditor 无需改变
/**
* 圆形
*/
class Circle extends Shape {
Circle() {
this.type = 2;
}
@Override
void draw() {
System.out.println(" 绘制圆形");
}
}