public interface State{
//声明抽象业务方法,不同的具体状态类实现不同
void handle(String parameter);
}
ConcreteState
public ConcreteState implements State{
public void handle(String parameter){
System.out.print("具体的业务逻辑");
}
}
Context
public class Context{
private State statee;
public setState(Status state){
this.state = state;
}
public void request(String arg){
...
state.handle(parameter);
...
}
}
public class Screen {
//枚举所有的状态,currentState表示当前状态
private State currentState, normalState, largerState, largestState;
public Screen() {
this.normalState = new NormalState(); //创建正常状态对象
this.largerState = new LargerState(); //创建二倍放大状态对象
this.largestState = new LargestState(); //创建四倍放大状态对象
this.currentState = normalState; //设置初始状态
this.currentState.display();
}
public void setState(Status state) {
this.currentState = state;
}
//单击事件处理方法,封转了对状态类中业务方法的调用和状态的转换
public void onClick() {
if (this.currentState == normalState) {
this.setState(largerState);
this.currentState.display();
}
else if (this.currentState == largerState) {
this.setState(largestState);
this.currentState.display();
}
else if (this.currentState == largestState) {
this.setState(normalState);
this.currentState.display();
}
}
}
State
public interface State{
void display();
}
ConcreteState:有三个
//正常状态
public class NormalState extends State{
public void display() {
System.out.println("正常大小!");
}
}
//二倍方法状态
public class LargerState extends State{
public void display() {
System.out.println("二倍大小!");
}
}
//四倍放大状态
public class LargestState extends State{
public void display() {
System.out.println("四倍大小!");
}
}
客户端
public class Client {
public static void main(String args[]) {
Screen screen = new Screen();
screen.onClick();
screen.onClick();
screen.onClick();
}
}
//输出如下
正常大小!
二倍大小!
四倍大小!
正常大小!