java面向?qū)ο笤O(shè)計(jì)原則之里氏替換原則示例詳解
概念
里氏替換原則是任何基類出現(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));
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ì)象。其代碼如下:
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)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring@Autowired與@Resource的區(qū)別有哪些
這篇文章主要為大家詳細(xì)介紹了@Autowired與@Resource的區(qū)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
Java圖片讀取ImageIO.read()報(bào)錯(cuò)問題及解決
在使用imageio庫讀取圖片時(shí),如果路徑中包含中文,可能會(huì)導(dǎo)致讀取失敗,解決方法是將路徑中的中文字符進(jìn)行轉(zhuǎn)義處理,可以使用ImageUtil.java工具類進(jìn)行路徑轉(zhuǎn)義,從而避免錯(cuò)誤,這是一個(gè)常見問題,希望本文的解決方案能幫助到遇到相同問題的開發(fā)者2024-10-10
教你利用JAVA實(shí)現(xiàn)可以自行關(guān)閉服務(wù)器的方法
今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識(shí),文章圍繞著利用JAVA實(shí)現(xiàn)可以自行關(guān)閉服務(wù)器的方法展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
spring @schedule注解如何動(dòng)態(tài)配置時(shí)間間隔
這篇文章主要介紹了spring @schedule注解如何動(dòng)態(tài)配置時(shí)間間隔,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11

