一、开闭原则介绍
开闭原则(Open Closed Principle)是编程中最基础,也是最重要的设计原则。编程中遵循其他原则以及使用设计模式的目的就是遵循开闭原则。
一个软件实体如类,模块和函数应该对(提供方)扩展开放,对(使用方)修改关闭。用抽象构建架构,用实现扩展细节。当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
二、案例讲解
实现一个画图形的功能,类图设计如下:
第一种解决方案:传统方案
代码实现如下:
public class Shape{
int type;
}
public class Rectangle extends Shape{
public Rectangle(){
super.type = 1;
}
}
public class Circle extends Shape{
public Circle(){
super.type = 2;
}
}
public class GraphicEditor{
public void drawShape(Shape s){
if(1 == s.type){
drawRectangle();
} else if(2 == s.type){
drawCircle();
}
}
public void drawRectangle(){
System.out.println("绘制矩形");
}
public void drawCircle(){
System.out.println("画圆形");
}
}
public class Test(){
public static void main(String[] args){
GraphicEditor editor = new GraphicEditor();
editor.drawShape(new Rectangle());
editor.drawShape(new Circle());
}
}
上面的实现方式比较好理解,简单易操作,但是如果这时要增加一个图形种类三角形,我们需要修改的地方很多,这就违反了开闭原则,即对扩展开放,对修改关闭。当我们给类添加新功能的时候,应该尽量不修改代码,或者尽可能少修改代码。
第二种解决方案:使用开闭原则
对上面代码改进思路:把创建Shape类做成抽象类,并提供一个抽象的draw方法,让子类去实现即可。这样有新的图形种类时,只需要让新的图形类继承Shape,并实现draw方法即可。使用方的代码就不需要修改,满足开闭原则。代码如下:
public abstract class Shape{
int type;
abstract void draw();
}
public class Rectangle extends Shape{
public Rectangle(){
super.type = 1;
}
public void draw(){
System.out.println("绘制矩形");
}
}
public class Circle extends Shape{
public Circle(){
super.type = 2;
}
public void draw(){
System.out.println("画圆形");
}
}
public class GraphicEditor{
public void drawShape(Shape s){
s.draw();
}
}
public class Test(){
public static void main(String[] args){
GraphicEditor editor = new GraphicEditor();
editor.draw(new Rectangle());
editor.draw(new Circle());
}
}
注:类Shape、Rectangle、Circle是提供方,类GraphicEditor是使用方