开闭原则

1. 开闭原则

开闭原则(Open Close Principle):

  • 开闭原则是编程中最基础、最重要的设计原则
  • 一个软件实体如类,模块和函数应该对扩展开放(对提供方),对修改关闭(对使用方)。用抽象构建框架,用实现扩展细节。
  • 当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
  • 面向接口编程

1.1 案例

  • 代码
public class OpenClosePrinceOne {
    public static void main(String[] args) {
        GraphicEditor graphicEditor =new GraphicEditor();
        graphicEditor.drawGraphice(new Rectangle());
        graphicEditor.drawGraphice(new Circle());
    }

}
//画图工具类 【使用方】
class GraphicEditor{
    public void drawGraphice(Shap shap){
        if(shap.type==1){
            drawRectangle();
        }
        if(shap.type==2){
            drawCircle();
        }
    }

    public void drawCircle() {
        System.out.println("画圆形");
    }

    public void drawRectangle() {
        System.out.println("画矩形");
    }
}
//基类
abstract class Shap{
    int  type;
}

//矩形
class  Rectangle extends Shap{
    Rectangle(){
        type=1;
    }
}
//圆形
class  Circle extends Shap{
    Circle(){
        type=2;
    }
}
  • 思考
    问题:如果现在要新增一个三角形呢,我们是不是要改动使用方(GraphicEditor),但是有没有办法不改变使用方呢?
    方案:开闭原则
  • 改进
public class OpenClosePrinceOne {
    public static void main(String[] args) {
        GraphicEditor graphicEditor =new GraphicEditor();
        graphicEditor.drawGraphice(new Rectangle());
        graphicEditor.drawGraphice(new Circle());
    }

}
//画图工具类 【使用方】
class GraphicEditor{
    public void drawGraphice(Shap shap) {
         shap.draw();
     }
}
abstract  class Shap{
    int  type;
    abstract  void draw();
}

//矩形
class  Rectangle extends Shap{
    Rectangle(){
        type=1;
    }

    @Override
    void draw() {
        System.out.println("画矩形");
    }
}

class  Circle extends Shap{
    Circle(){
        type=2;
    }

    @Override
    void draw() {
        System.out.println("画圆形");
    }
}

1.2 总结

  • 使用方通过使用抽象来避免修改(接口、抽象类),提供方通过实现抽象来扩展功能。
  • 开闭原则是最基本,也是最重要的一个原则
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值