![](/img/trans.png)
[英]Java TreeMaps with inheritance without instanceOf
[英]How to prevent inheritance from breaking all dependencies in OOP manner without instanceof or typecasting?
我們正在為飛機上的所有座位計費。 最初,我們每個席位都有折扣。 假設我們有一個Discount
類,並且依賴於它的seat-billing
和audit
代碼。
class Discount {
private int discountId; // unique key stored in database
public int getDiscountId() {
return discountId;
}
public List<Seat> getListOfSeatsWithDiscount() {
}
public int getDiscountPercentPerSeat() { return 10; }
}
class SeatBill {
public void billPerSeat() {
for (each seat object) {
// fetch discountObject from database.
Discount d;
// get list of seats with discounts, and for each of such seats
seatObject.totalCost = seatObject.totalCost * (100 - d.getDiscountPercentPerSeat())/100;
}
}
}
然后我們有一個審計班,關心打折座位。
class Audit {
public void audit(Discount id) {
// fetch discount object from database given discount id.
for (seat in d.getListOfSeatsWithDiscount()) {
// log all the seats.
}
}
}
現在飛機管理人員決定增加另一個折扣->假期的每月折扣。 因此,我們創建了一個抽象類Discount
並創建了DiscountPerSeat
和DiscountPerMonth
。
abstract class Discount {
private int discountId; // unique key stored in database
public int getDiscountId() {
return discountId;
}
}
class DiscountPerSeat extends Discount {
public List<Seat> getListOfSeatsWithDiscount() {
}
// returns 10% discount on each seat reserved.
public int getDiscountPercentPerSeat() { return 10; }
}
class DiscountPerMonth extends Discount {
public boolean checkIfMonthIsValid(int month) {
return month == 12;
}
// returns 10% discount on monthly bill
public int getDiscountPercentPerMonth() { return 10; }
}
現在,每月帳單代碼將更改。
class MonthlyBill {
public int monthlyBillPerPersonOrCompany(int id) {
int totalCostPerEntity = gettotalCost(id);
// fetch discount object from database
// apply discount if 'current month' is december'
totalCostPerEntity = totalCostPerEntity * (100 - (disCountPerMonth.getDiscountPercentPerMonth()))/100
}
}
現在我的問題是:
審計類已損壞,因為getListOfSeatsWithDiscount
已移入其抽象方法getListOfSeatsWithDiscount
的子類中。 如何在不使用typecaseting / instanceof的情況下進行修復?
由於抽象類Discount不支持getDiscountPercentPerSeat,所以SeatBill類已損壞。 如何在不進行typecasting / instanceof的情況下解決此問題?
MonthlyBill將從數據庫中獲取折扣對象。 再次如何在不依賴實例的情況下以OOP方式解決此問題?
基本上,由於代碼依賴於子類的特定方法(如getListOfSeats
或getValidMonth
等),因此無法在代碼庫中打破很多依賴關系,這些子方法無法抽象到基類。
請讓我知道這種重構的通用解決方案/設計模式。
要解決問題1,您需要聲明public abstract List<Seat> getListOfSeatsWithDiscount();
在折扣。 然后,您還需要在DiscountPerMonth中定義getListOfSeatsWithDiscount()
。 如果審計應該僅與DiscountPerSeat一起使用,則只需在Audit中使用DiscountPerSeat(而不是Discount)。
要解決問題2,您需要聲明public abstract int getDiscount();
在Discount中,然后將DiscountPerSeat和DiscountPerMonth中的方法重命名為getDiscount()。
問題3應該通過問題2的解決方案來解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.