开闭原则: 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已
有的代码来实现变化。
开闭原则代码1:(未能遵循开闭原则,存在优化的空间)
/**
* 开闭原则代码1
*/
public class oncg {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
graphicEditor.drawShape(new Triangle());
}
}
/**
* 用于绘图的类[使用方]
*/
class GraphicEditor {
// 接收 Shape 对象,然后根据 type, 来绘制不同的图形
public void drawShape(Shape s) {
if (s.m_typte == 1) {
drawRectangle(s);
} else if (s.m_typte == 2) {
drawCircle(s);
} else if (s.m_typte == 3) {
drawTriangle(s);
}
}
// 绘制矩形
public void drawRectangle(Shape s) {
System.out.println(" 绘制矩形 ");
}
// 绘制圆形
public void drawCircle(Shape s) {
System.out.println(" 绘制圆形 ");
}
public void drawTriangle(Shape s) {
System.out.println(" 绘制三角形 ");
}
}
/**
* Shape类,基类
*/
class Shape {
int m_typte;
}
/**
* 矩形实体类
*/
class Rectangle extends Shape {
Rectangle() {
super.m_typte = 1;
}
}
/**
* 圆形实体类
*/
class Circle extends Shape {
Circle() {
super.m_typte = 2;
}
}
/**
* 三角形实体类
*/
class Triangle extends Shape {
Triangle() {
super.m_typte = 3;
}
}
解析:违反了OCP原则,新增一个新的类,比如三角形,我们需要修改的地方较多;优化方案将使用ocp原则,请看下篇;