- 设计模式-状态模式
- 设计模式-主页
- 设计模式-概述
- 设计模式-工厂模式
- 抽象工厂模式
- 设计模式-Singleton模式
- 设计模式-生成器模式
- 设计模式-原型模式
- 设计模式-适配器模式
- 设计模式-桥梁模式
- 设计模式-过滤器模式
- 设计图案-复合图案
- 设计图案-装饰图案
- 设计图案-立面图案
- 设计图案-飞线图案
- 设计模式-代理模式
- 责任链模式
- 设计模式-命令模式
- 设计模式-解释器模式
- 设计模式-迭代器模式
- 设计模式-中介模式
- 设计模式-Memento模式
- 设计模式-观察者模式
- 设计模式-状态模式
- 设计模式-空对象模式
- 设计模式-战略模式
- 设计模式-模板模式
- 设计模式-访客模式
- 设计模式-MVC模式
- 业务代表模式
- 复合实体模式
- 数据访问对象模式
- 前控制器模式
- 拦截过滤器模式
- 服务定位器模式
- Java传输对象模式
设计模式-状态模式
In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.
Implementation
We are going to create a State interface defining an action and concrete state classes implementing the State interface. Context is a class which carries a State.
StatePatternDemo, our demo class, will use Context and state objects to demonstrate change in Context behavior based on type of state it is in.
Step 1
Create an interface.
State.java
public interface State { public void doAction(Context context); }
Step 2
Create concrete classes implementing the same interface.
StartState.java
public class StartState implements State { public void doAction(Context context) { System.out.println("Player is in start state"); context.setState(this); } public String toString(){ return "Start State"; } }
StopState.java
public class StopState implements State { public void doAction(Context context) { System.out.println("Player is in stop state"); context.setState(this); } public String toString(){ return "Stop State"; } }
Step 3
Create Context Class.
Context.java
public class Context { private State state; public Context(){ state = null; } public void setState(State state){ this.state = state; } public State getState(){ return state; } }
Step 4
Use the Context to see change in behaviour when State changes.
StatePatternDemo.java
public class StatePatternDemo { public static void main(String[] args) { Context context = new Context(); StartState startState = new StartState(); startState.doAction(context); System.out.println(context.getState().toString()); StopState stopState = new StopState(); stopState.doAction(context); System.out.println(context.getState().toString()); } }
Step 5
Verify the output.
Player is in start state Start State Player is in stop state Stop State