设计模式--开闭原则

对拓展开放、对修改关闭

有两种理解

  • 模块应该在尽量不修改代码的前提下进行拓展
  • 提供方的变动不会引起使用方的修改

这就指导我们用抽象来构建框架,用实现拓展细节

上一段代码,根据图形代码画图形

class Shape {
    int type;
}
/**
 * 矩形
 */
class Rectangle extends Shape {
    Rectangle() {
        this.type = 1;
    }
}
/**
 * 这是绘制图形的类
 */
class GraphicEditor {
    public void drawShape(Shape shape) {
        if (shape.type == 1) {
            System.out.println(" 绘制矩形");
        }
    }
}

思考一下,现在要新增画圆形的方法,代码如下

/**
 * 新增矩形类圆形
 */
class Circle extends Shape {
    Circle() {
        this.type = 2;
    }
}
/**
 * 修改绘制图形的类
 */
class GraphicEditor {
    public void drawShape(Shape shape) {
        if (shape.type == 1) {
            System.out.println(" 绘制矩形");
        }
        if (shape.type == 2) {
            System.out.println(" 绘制圆形");
        }
    }
}

看到没,上面的代码拓展了圆形类,使用方GraphicEditor也得跟着改,违背了开闭原则,修改后如下

/**
 * 修改为抽象类
 */
 abstract class Shape {
    int type;
    abstract  void draw();
}
/**
 * 矩形
 */
class Rectangle extends Shape {
    Rectangle() {
        this.type = 1;
    }

    @Override
    void draw() {
        System.out.println(" 绘制矩形");
    }
}
/**
 * 绘制图形的类
 */
class GraphicEditor {
    public void drawShape(Shape shape) {
        shape.draw();
    }
}

看到没,现在想画圆形,只需新增一个圆形类,使用者GraphicEditor 无需改变

/**
 * 圆形
 */
class Circle extends Shape {
    Circle() {
        this.type = 2;
    }
    
    @Override
    void draw() {
        System.out.println(" 绘制圆形");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值