设计模式-开放封闭原则

在上一篇文章中我回顾了下单一职责原则,在这篇文章中我来复习下开放-封闭原则
开放封闭原则:开放扩展,关闭修改。当一个业务系统稳定了,当有新增的业务的时候采用增加类的方式来拓展,替代直接对原有业务类的修改。可以利用面向对象继承和多态这两个特性来实现。对业务逻辑进行抽象,将具体业务的实现发放到子类中,这样当业务逻辑发生变化的时候我们就可以通过新增子类的方式来实现业务扩展。
例如:计算器有加,减,乘,除四种方法。

/**
 * @author  Created by yanjy on 2017/11/4.
 */
public class Calculator {

    public int add(int a, int b) {
        return a + b;
    }

    public int sub(int a, int b) {
        return a - b;
    }

    public static void main(String[] args) {
        Calculator calculator = new Calculator();

        calculator.add(1, 3);
        calculator.sub(3, 2);
    }
}

这个计算器类当要新增加乘除运算,需要修改Calculter,这就违反了封闭原则,在这个时候我们就该考虑对计算器的业务逻辑进行提取,让他专注于对外提供计算服务而由实现者来提供业务逻辑的实现。

/**
 * @author Created by yanjy on 2017/11/4.
 */
public interface CalculatorInter<T> {
    /**
     * calculator
     * @param a
     * @param b
     * @return
     */
    T calculate(T a, T b);
}

/**
 * @author Created by yanjy on 2017/11/4.
 */
public class AddCalculatorImpl implements CalculatorInter {
    @Override
    public Object calculate(Object a, Object b) {
        return (int) a + (int) b;
    }
}

/**
 * @author Created by yanjy on 2017/11/4.
 */
public class DivideCalculatorImpl implements CalculatorInter {
    @Override
    public Object calculate(Object a, Object b) {
        return (int) b != 0 ? (int) a / (int) b : null;
    }
}

/**
 * @author Created by yanjy on 2017/11/4.
 */
public class SubCalculatorImpl implements CalculatorInter {
    @Override
    public Object calculate(Object a, Object b) {
        return (int) a - (int) b;
    }
}

/**
 * @author Created by yanjy on 2017/11/4.
 */
public class MultiCalculatorImpl implements CalculatorInter {
    @Override
    public Object calculate(Object a, Object b) {
        return (int) a * (int) b;
    }
}

/**
 * @author Created by yanjy on 2017/11/4.
 */
public class DivideCalculatorImpl implements CalculatorInter {
    @Override
    public Object calculate(Object a, Object b) {
        return (int) b != 0 ? (int) a / (int) b : null;
    }
}


/**
 * @author Created by yanjy on 2017/11/4.
 */
public class ShowCalculator {
    public static void main(String[] args) {
        CalculatorInter add = new AddCalculatorImpl();
        CalculatorInter sub = new SubCalculatorImpl();
        CalculatorInter mul = new MultiCalculatorImpl();
        CalculatorInter divide = new DivideCalculatorImpl();

        add.calculate(1, 3);
        sub.calculate(3, 6);
        mul.calculate(3, 5);
        divide.calculate(3, 6);
    }
}

这样进行修改后如果要新增加根号计算方法,新写一个根号类就能进行业务扩展了。在实际应用中面对复杂的业务逻辑我们很难做出准确的预测,要尽量避免过度的对业务逻辑进行猜想抽象,而应在增加新逻辑的过程中去发现问题,然后在对我们的代码进行更加成熟的抽象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值