State接口类
public interface State {
void handle();
}
BookedState类
/**CheckedInState类
* 已预订状态
* @author Administrator
*
*/
public class BookedState implements State {
@Override
public void handle() {
System.out.println("房间已预订!别人不能定!");
}
}
/**FreeState类
* 已入住状态
* @author Administrator
*
*/
public class CheckedInState implements State {
@Override
public void handle() {
System.out.println("房间已入住!请勿打扰!");
}
}
/**HomeContext类
* 空闲状态
* @author Administrator
*
*/
public class FreeState implements State {
@Override
public void handle() {
System.out.println("房间空闲!!!没人住!");
}
}
/**Client测试类
* 房间对象
* @author Administrator
*
*/
public class HomeContext {
//如果是银行系统,这个Context类就是账号。根据金额不同,切换不同的状态!
private State state;
public void setState(State s){
System.out.println("修改状态!");
state = s;
state.handle();
}
}
public class Client {
public static void main(String[] args) {
HomeContext ctx = new HomeContext();
ctx.setState(new FreeState());
ctx.setState(new BookedState());
}
}