什么是开闭原则?
开闭原则(Open Closed Principle), 简称OCP。是编程中最基础、最重要的设计原则
一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节
当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
编程中遵循其他原则,以及使用设计模式的目的目的就是遵循开闭原则
为什么要设计开闭原则
(1) 方便代码的可扩展性
(2) 减少代码的复杂性
(3) 遵循对扩展开放,对修改关闭
案例演示01 - 非开闭原则
有一个绘制图形的类,根据传入不同类型的Shape再判断绘制不同类型的图形
public class Normal {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.draw(new Rectangle());
graphicEditor.draw(new Circle());
graphicEditor.draw(new Triangle());
}
}
class GraphicEditor {
public void draw(Shape shape) {
if (shape.type == 1) {
drawRectangle();
}else if (shape.type == 2) {
drawCircle();
}else if (shape.type == 3) {
drawTriangle();
}
}
private void drawRectangle() {
System.out.println("绘制矩形");
}
private void drawCircle() {
System.out.println("绘制圆型");
}
private void drawTriangle() {
System.out.println("绘制三角形");
}
}
class Shape {
int type;
}
class Rectangle extends Shape {
public Rectangle() {
super.type = 1;
}
}
class Circle extends Shape {
public Circle() {
super.type = 2;
}
}
class Triangle extends Shape {
public Triangle() {
super.type = 3;
}
}
这种编写方式表简单,但是可扩展性和代码维护性不高。严重违反了设计模式的OCP原则,即对扩展开放(提供方),
对修改关闭(使用方)。当给我们的类增加新功能时,尽量不要修改代码或更少可能修改代码。如果下面需要再绘制
一个平行四边形,那么需要修改很多地方,不利于维护
案例演示02 - 开闭原则
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.draw(new Rectangle());
graphicEditor.draw(new Circle());
graphicEditor.draw(new Triangle());
graphicEditor.draw(new Parallelogram());
}
}
abstract class Shape {
int type;
public abstract void draw();
}
class Rectangle extends Shape {
public Rectangle() {
super.type = 1;
}
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
class Circle extends Shape {
public Circle() {
super.type = 2;
}
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
class Triangle extends Shape {
public Triangle() {
super.type = 3;
}
@Override
public void draw() {
System.out.println("绘制三角形");
}
}
class Parallelogram extends Shape {
public Parallelogram() {
super.type = 4;
}
@Override
public void draw() {
System.out.println("绘制平行四边形");
}
}
class GraphicEditor {
public void draw(Shape shape) {
shape.draw();
}
}
基于抽象类的形式,把Shape类做成抽象类,并提供一个抽象的draw方法,让子类实现即可,这样如果有新的图形种类
只需要让其继承Shape基类,并实现draw方法即可。这样就可以做到不修改代码的前提下完成功能,满足了开闭原则