开闭原则(Open Closed Principle)
基本介绍
- 开闭原则是编程中最基础、最重要的设计原则
- 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现展示细节。
- 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有代码来实现变化。
- 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则。
示例
public class Ocp {
public static void main(String[] args) {
//使用看看存在的问题
GraphicEditor graphicEditor=new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
}
}
//这是一个用于绘图的类
class GraphicEditor{
public void drawShape(Shape s){
//接收Shape对象,然后根据type,来绘制不同的图形
if(s.m_type==1){
drawRectangle(s);
}else if(s.m_type==2){
drawCircle(s);
}
}
public void drawRectangle(Shape r){
System.out.println("绘制矩形");
}
public void drawCircle(Shape r){
System.out.println("绘制圆形");
}
}
//Shape类,基类
class Shape{
int m_type;
}
class Rectangle extends Shape{
public Rectangle() {
super.m_type=1;
}
}
class Circle extends Shape{
public Circle() {
super.m_type=2;
}
}
该方式优缺点:
- 优点比较好理解,简单易操作
- 缺点是违反了设计模式的ocp原则,即对扩展开放(提供方),对修改关闭(使用方)
改进思路:
1、Shape类改为抽象类,提供一个抽象的draw方法,子类继承Shape实现draw方法即可满足ocp原则
public class Ocp {
public static void main(String[] args) {
GraphicEditor graphicEditor=new GraphicEditor();
graphicEditor.drawShape(new Rectangle());
graphicEditor.drawShape(new Circle());
}
}
//这是一个用于绘图的类
class GraphicEditor{
public void drawShape(Shape s){
s.draw();
}
}
//Shape类,基类
abstract class Shape{
int m_type;
public abstract void draw();
}
class Rectangle extends Shape {
public Rectangle() {
super.m_type=1;
}
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
class Circle extends Shape {
public Circle() {
super.m_type=2;
}
@Override
public void draw() {
System.out.println("绘制圆形");
}
}