概念
里氏替換原則是任何基類出現(xiàn)的地方,子類一定可以替換它;是建立在基于抽象、多態(tài)、繼承的基礎(chǔ)復(fù)用的基石,該原則能夠保證系統(tǒng)具有良好的拓展性,同時(shí)實(shí)現(xiàn)基于多態(tài)的抽象機(jī)制,能夠減少代碼冗余。
實(shí)現(xiàn)
里氏替換原則要求我們?cè)诰幋a時(shí)使用基類或接口去定義對(duì)象變量,使用時(shí)可以由具體實(shí)現(xiàn)對(duì)象進(jìn)行賦值,實(shí)現(xiàn)變化的多樣性,完成代碼對(duì)修改的封閉,擴(kuò)展的開放。如:商城商品結(jié)算中,定義結(jié)算接口Istrategy,該接口有三個(gè)具體實(shí)現(xiàn)類,分別為PromotionalStrategy (滿減活動(dòng),兩百以上百八折)、RebateStrategy (打折活動(dòng))、 ReduceStrategy(返現(xiàn)活動(dòng));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public interface Istrategy { public double realPrice( double consumePrice); } public class PromotionalStrategy implements Istrategy { public double realPrice( double consumePrice) { if (consumePrice > 200 ) { return 200 + (consumePrice - 200 ) * 0.8 ; } else { return consumePrice; } } } public class RebateStrategy implements Istrategy { private final double rate; public RebateStrategy() { this .rate = 0.8 ; } public double realPrice( double consumePrice) { return consumePrice * this .rate; } } public class ReduceStrategy implements Istrategy { public double realPrice( double consumePrice) { if (consumePrice >= 1000 ) { return consumePrice - 200 ; } else { return consumePrice; } } } |
調(diào)用方為Context,在此類中使用接口定義了一個(gè)對(duì)象。其代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class Context { //使用基類定義對(duì)象變量 private Istrategy strategy; // 注入當(dāng)前活動(dòng)使用的具體對(duì)象 public void setStrategy(Istrategy strategy) { this .strategy = strategy; } // 計(jì)算并返回費(fèi)用 public double cul( double consumePrice) { // 使用具體商品促銷策略獲得實(shí)際消費(fèi)金額 double realPrice = this .strategy.realPrice(consumePrice); // 格式化保留小數(shù)點(diǎn)后1位,即:精確到角 BigDecimal bd = new BigDecimal(realPrice); bd = bd.setScale( 1 , BigDecimal.ROUND_DOWN); return bd.doubleValue(); } } |
Context 中代碼使用接口定義對(duì)象變量,這個(gè)對(duì)象變量可以是實(shí)現(xiàn)了lStrategy接口的PromotionalStrategy、RebateStrategy 、 ReduceStrategy任意一個(gè)。
拓展
里氏替換原則和依賴倒置原則,構(gòu)成了面向接口編程的基礎(chǔ),正因?yàn)槔锸咸鎿Q原則,才使得程序呈現(xiàn)多樣性。
以上就是java面向?qū)ο笤O(shè)計(jì)原則之里氏替換原則示例詳解的詳細(xì)內(nèi)容,更多關(guān)于java面向?qū)ο笤O(shè)計(jì)里氏替換原則的資料請(qǐng)關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://blog.csdn.net/guoyp2126/article/details/113919502