Welcome

首页 / 软件开发 / 数据结构与算法 / 状态模式(state pattern) 详解

状态模式(state pattern) 详解2016-03-29状态模式(state pattern): 允许对象在内部状态改变时改变它的行为, 对象看起来好像修改了它的类.

建立Context类, 包含多个具体状态(concrete state)类的组合, 根据状态的不同调用具体的方法, state.handle(), 包含setget方法改变状态.

状态接口(state interface), 包含抽象方法handle(), 具体状态类(concrete state)继承(implement)状态类(state), 实现handle()方法;

具体方法:

1. Context类, 组合多个具体状态类(concrete state), 并提供setget方法, 调用状态的方法(handle), 改变状态.

/*** @time 2014年7月11日*/package state.pattern;/*** @author C.L.Wang**/public class GumballMachine {State soldOutState;State noQuarterState;State hasQuarterState;State soldState;State winnerState;State state = soldOutState;int count = 0;/*** */public GumballMachine(int numberGumballs) {// TODO Auto-generated constructor stubsoldOutState = new SoldOutState(this);noQuarterState = new NoQuarterState(this);hasQuarterState = new HasQuarterState(this);soldState = new SoldState(this);winnerState = new WinnerState(this);this.count = numberGumballs;if (numberGumballs > 0) {state = noQuarterState;}}public void insertQuarter() {state.insertQuarter();}public void ejectQuarter() {state.ejectQuater();}public void turnCrank() {state.turnCrank();state.dispense();}void setState(State state) {this.state = state;}void releaseBall() {System.out.println("A gumball comes rolling out the slot...");if (count != 0)count --;}int getCount() {return count;}void refill(int count) {this.count = count;state = noQuarterState;}public State getState() {return state;}public State getSoldOutState() {return soldOutState;}public State getNoQuarterState() {return noQuarterState;}public State getHasQuarterState() {return hasQuarterState;}public State getSoldState() {return soldState;}public State getWinnerState() {return winnerState;}public String toString() {StringBuffer result = new StringBuffer();result.append("
Mighty Gumball, Inc.");result.append("
Java-enabled Standing Gumball Model #2004
");result.append("Inventory: " + count + " gumball");if (count != 1) {result.append("s");}result.append("
Machine is " + state + "
");return result.toString();}}