在酒店管理系统中,酒店房间的状态是不断变化:有已预订、已入住、空闲状态。应用状态模式,用Java改进该设计
时间: 2024-03-12 22:43:14 浏览: 87
酒店管理系统,适用java
好的,我理解了你的问题。在酒店管理系统中,酒店房间的状态是不断变化的,可以使用状态模式来改进该设计。状态模式是一种行为模式,它允许对象在其内部状态改变时改变其行为。在这种情况下,酒店房间的状态就是其内部状态,而其行为取决于其状态。
首先,我们需要定义一个状态接口(RoomState),其具有三个方法:预订(book)、入住(checkIn)和退房(checkOut)。然后,我们需要为酒店房间的每种状态实现一个具体状态类,并在这些类中实现这些方法。最后,我们需要在酒店房间类(Room)中维护一个当前状态对象,并在该类中调用当前状态对象的方法。
下面是代码示例:
```java
//定义状态接口
public interface RoomState {
void book(Room room);
void checkIn(Room room);
void checkOut(Room room);
}
//已预订状态
public class BookedState implements RoomState {
@Override
public void book(Room room) {
System.out.println("The room is already booked.");
}
@Override
public void checkIn(Room room) {
System.out.println("Checking in...");
room.setState(new CheckedInState());
}
@Override
public void checkOut(Room room) {
System.out.println("Cannot check out, the room is already booked.");
}
}
//已入住状态
public class CheckedInState implements RoomState {
@Override
public void book(Room room) {
System.out.println("Cannot book, the room is already checked in.");
}
@Override
public void checkIn(Room room) {
System.out.println("The room is already checked in.");
}
@Override
public void checkOut(Room room) {
System.out.println("Checking out...");
room.setState(new VacantState());
}
}
//空闲状态
public class VacantState implements RoomState {
@Override
public void book(Room room) {
System.out.println("Booking...");
room.setState(new BookedState());
}
@Override
public void checkIn(Room room) {
System.out.println("Cannot check in, the room is not booked.");
}
@Override
public void checkOut(Room room) {
System.out.println("Cannot check out, the room is already vacant.");
}
}
//酒店房间类
public class Room {
private RoomState state;
public Room() {
state = new VacantState();
}
public void setState(RoomState state) {
this.state = state;
}
public void book() {
state.book(this);
}
public void checkIn() {
state.checkIn(this);
}
public void checkOut() {
state.checkOut(this);
}
}
```
现在我们可以在主函数中测试我们的实现:
```java
public static void main(String[] args) {
Room room = new Room();
room.book();
room.book();
room.checkIn();
room.checkOut();
room.checkOut();
room.book();
room.checkIn();
}
```
输出应该如下所示:
```
Booking...
The room is already booked.
Checking in...
Checking out...
Cannot check out, the room is already vacant.
Booking...
Checking in...
```
阅读全文