設計模式-開放封閉原則

在上一篇文章中我回顧了下單一職責原則,在這篇文章中我來複習下開放-封閉原則
開放封閉原則:開放擴展,關閉修改。當一個業務系統穩定了,當有新增的業務的時候採用增加類的方式來拓展,替代直接對原有業務類的修改。可以利用面向對象繼承和多態這兩個特性來實現。對業務邏輯進行抽象,將具體業務的實現發放到子類中,這樣當業務邏輯發生變化的時候我們就可以通過新增子類的方式來實現業務擴展。
例如:計算器有加,減,乘,除四種方法。

/**
 * @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);
    }
}

這樣進行修改後如果要新增加根號計算方法,新寫一個根號類就能進行業務擴展了。在實際應用中面對複雜的業務邏輯我們很難做出準確的預測,要儘量避免過度的對業務邏輯進行猜想抽象,而應在增加新邏輯的過程中去發現問題,然後在對我們的代碼進行更加成熟的抽象。

發佈了25 篇原創文章 · 獲贊 0 · 訪問量 2846
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章