设计模式 状态模式
程序员文章站
2022-03-14 20:50:09
...
解决 对象发生变化时 其所能做的操作也会发生变化
酒店房间定房系统 房间状态
如果空闲的时候可以 预定房间 也可以入住 这样的判断 会让代码有很多的逻辑
state模式代码实现订房系统
public abstract class abState
{
public abstract string getState();
public abstract void book(Room room);
public abstract void checkin(Room room);
public abstract void unbook(Room room);
public abstract void checkout(Room room);
}
public class Room
{
private abState state;
public string GetState()
{
return this.state.getState();
}
public void setState(abState _state)
{
state = _state;
}
public void book()
{
this.state.book(this);
}
public void unbook()
{
this.state.unbook(this);
}
public void checkin()
{
this.state.checkin(this);
}
public void checkout()
{
this.state.checkout(this);
}
}
class BookState : abState
{
public override string getState()
{
return "当前为预订状态";
}
public override void book(Room room)
{
Console.WriteLine("当前为预订状态,无法再次预订操作");
}
public override void checkin(Room room)
{
Console.WriteLine("当前为预订状态,行进入住操作");
room.setState(new CheckinState());
}
public override void unbook(Room room)
{
Console.WriteLine("当前为预订状态,进行取消操作");
room.setState(new FreeState());
}
public override void checkout(Room room)
{
Console.WriteLine("当前为预订状态,无法进行退房操作");
}
}
class CheckinState : abState
{
public override string getState()
{
return "当前为入住状态";
}
public override void book(Room room)
{
Console.WriteLine("当前为入住状态,无法进行预订操作");
// room.setState(new BookState());
}
public override void checkin(Room room)
{
Console.WriteLine("当前为入住状态,无法入住操作");
}
public override void unbook(Room room)
{
Console.WriteLine("当前为入住状态,无法取消预订操作");
}
public override void checkout(Room room)
{
Console.WriteLine("当前为入住状态,进行退房操作");
room.setState(new FreeState());
}
}
class FreeState:abState
{
public override string getState()
{
return "当前为空闲状态";
}
public override void book(Room room)
{
Console.WriteLine("当前为空闲状态,进行预订操作");
room.setState(new BookState());
}
public override void checkin(Room room)
{
Console.WriteLine("当前为空闲状态,行进入住操作");
room.setState(new CheckinState());
}
public override void unbook(Room room)
{
Console.WriteLine("当前为空闲状态,无法取消预约");
}
public override void checkout(Room room)
{
Console.WriteLine("当前为空闲状态,无法进行退房操作");
}
}
Room room = new Room();
abState s = new FreeState();
room.setState(s);
Console.WriteLine("======================");
Console.WriteLine(room.GetState());
Console.WriteLine("======================");
room.checkin();
Console.WriteLine(room.GetState());
Console.WriteLine("======================");
room.book();
Console.WriteLine(room.GetState());
Console.WriteLine("======================");
room.checkout();
Console.WriteLine(room.GetState());
Console.WriteLine("======================");
Console.ReadKey();
上一篇: 设计模式-状态模式