在Room 和Suite 类中都有一个单独的static 字段是最快/最简单的解决方案。
Room
_________|_______
/ \
Standard Suite
| |
`static int price; `static int price;
或者,您可以在 Room 类中创建一个 static Map<Class<? extends Room>, Integer>,该类存储每个 Room 类型的基本价格。
public class Room {
private static Map<Class<? extends Room>, Integer> prices =
new HashMap<>();
public final int getRoomBasePrice() {
// If a Room subclass does not have a specific base price, return
// 1000 by default.
return Room.prices.getOrDefault(this.getClass(), 1000);
}
/** Sets the base price for the specified Room type.
*/
public final void setRoomBasePrice(int price) {
Room.prices.put(this.getClass(), price);
}
}
使用上面的代码将确保价格在类的所有实例中保持不变。
mySuite.setRoomBasePrice(2000);
(new Suite()).getRoomBasePrice(); // -> 2000
编辑:经过重新考虑,我意识到使用static 不是解决问题的正确方法,因为它会使代码变脆且难以更改。
最好的方法是有一个单独的RoomPriceService 类,它提供了一个查询来获取特定房间类型的价格。
public class RoomPriceService {
private Map<Class<? extends RoomType>, Integer> prices;
public RoomPriceService(int defaultPrice) {
this.prices = new HashMap();
}
public void setPriceOfRoomType(Room r, Integer price) {
this.prices.set(r.getClass(), price);
}
public Integer getPriceOfRoomType(Room r) {
// You can expand on this code by adding setters/getters for
// setting and getting the default room price.
return this.prices.getOrDefault(r.getClass(), 100);
}
}
这样,您可以拥有多个 RoomPriceService 实例,这些实例可以存储不同情况下的价格(例如,您可以为每个季节拥有一个 RoomPriceService,或为不同的促销活动创建一个 RoomPriceService,等等)。