标签:
GOF:允许一个对象在其内部状态发生变化时改变自己的行为,该对象看起来好像修改了它的类型。
状态模式就是将switch(state)这样的状态判断的长方法抽象到state类中,便于维护和修改。
模板:
interface State { public void Handle(Context context); } class StateA implements State { public void Handle(Context context) { context.State = new StateB(); } } class StateB implements State { public void Handle(Context context) { context.State = new StateC(); } } class StateC implements State { public void Handle(Context context) { context.State = new StateA(); } } class Context { private State state; public Context(State state) { this.state = state; } public void Request() { state.Handle(this); } public static void main(String[] args) { Context c = new Context(new StateA()); c.Request(); c.Request(); c.Request(); } } }
实例:
/* 该模式是用于消除复杂的switch/if-else结构,并保障OCP原则 */ public class 状态模式 { public static void main(String[] args) { PaintBoard paintBoard = new PaintBoard(); System.out.println("Push test: "); System.out.println("Paint board current color:" + paintBoard.getCurrentColor()); for(int i=0; i<3; i++) { System.out.printf("%s ---push---> ", paintBoard.getCurrentColor()); paintBoard.push(); System.out.println(paintBoard.getCurrentColor()); } System.out.println("Pull test: "); System.out.println("Paint board current color:" + paintBoard.getCurrentColor()); for(int i=0; i<3; i++) { System.out.printf("%s ---pull---> ", paintBoard.getCurrentColor()); paintBoard.pull(); System.out.println(paintBoard.getCurrentColor()); } } } class PaintBoard { private State state = new RedState(); public String getCurrentColor() { return state.name(); } public void setState(State state ) { this.state = state; } public void push() { state.push(this); } public void pull() { state.pull(this); } } //借口 interface State { void push(PaintBoard paintBoard); void pull(PaintBoard paintBoard); String name(); } //下面三种颜色分别实现该接口 class RedState implements State { @Override public void push(PaintBoard paintBoard) { paintBoard.setState(new GreenState()); } @Override public void pull(PaintBoard paintBoard) { paintBoard.setState(new BlueState()); } @Override public String name() { return "RED"; } } class GreenState implements State { @Override public void push(PaintBoard paintBoard) { paintBoard.setState(new BlueState()); } @Override public void pull(PaintBoard paintBoard) { paintBoard.setState(new RedState()); } @Override public String name() { return "GREEN"; } } class BlueState implements State { @Override public void push(PaintBoard paintBoard) { paintBoard.setState(new RedState()); } @Override public void pull(PaintBoard paintBoard) { paintBoard.setState(new GreenState()); } @Override public String name() { return "BLUE"; } }
与策略模式的联系与区别:
(1)都将变化的部分放到其他类中。
(2)状态模式隐藏了状态接口和子类,策略模式的策略接口和实现都是可见(需要用户自己选择)。
标签:
原文地址:http://www.cnblogs.com/programmer-kaima/p/4373584.html