状态模式(State)
对象行为的变化是由于状态的变化引入,那么即当内部状态发生变化的时候,就会改变对象的行为,而这种改变视乎就改变了整个类。
package com.xiaoqiang.gof23.actionnModel.state;
/**
* @author xiaoqiang
* @date $(DATE)-$(TIME)
* 状态类
*/
public interface State {
void handle();
}
package com.xiaoqiang.gof23.actionnModel.state;
/**
* @author xiaoqiang
* @date $(DATE)-$(TIME)
* 房间类
*/
public class Home {
private State state;
public void setState(State state) {
System.out.println("修改状态");
this.state = state;
state.handle();
}
}
package com.xiaoqiang.gof23.actionnModel.state;
/**
* @author xiaoqiang
* @date $(DATE)-$(TIME)
*/
public class FreeState implements State {
@Override
public void handle() {
System.out.println("房间空闲,没人住");
}
}
package com.xiaoqiang.gof23.actionnModel.state;
/**
* @author xiaoqiang
* @date $(DATE)-$(TIME)
*/
public class BookedState implements State {
@Override
public void handle() {
System.out.println("房间有人预定了");
}
}
package com.xiaoqiang.gof23.actionnModel.state;
/**
* @author xiaoqiang
* @date $(DATE)-$(TIME)
*/
public class CheckedState implements State {
@Override
public void handle() {
System.out.println("'有人住了");
}
}
package com.xiaoqiang.gof23.actionnModel.state;
/**
* @author xiaoqiang
* @date $(DATE)-$(TIME)
*/
public class Client {
public static void main(String[] args) {
Home home = new Home();
home.setState(new FreeState());
}
}