静态成员继承和通过Java中的子成员访问

时间:2017-09-20 12:26:36

标签: java oop static

我在这里有以下案例:

  Room { price; }
        |
      ------
    /        \
standard    suite

我想设置标准房间的价格,使其在standard的所有情况下保持静止,并且不得影响suite的价格,反之亦然。我已尝试在priceRoom中保留static并通过子类中的getter和setter访问它,但它不起作用。我也不愿意在每个孩子班级中成为price成员,因为我不喜欢这个解决方案。也许还有另一个漂亮的OOP解决方案。

1 个答案:

答案 0 :(得分:-1)

staticRoom类中都有单独的Suite字段是最快捷/最简单的解决方案。

            Room
     _________|_______
    /                 \
Standard               Suite
|                      |
 `static int price;     `static int price;

或者,您可以在static Map<Class<? extends Room>, Integer>类中创建Room,其中存储每种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促销等)。