前言:【模式总览】——————————by xingoohtml
容许一个对象在内部改变它的状态,并根据不一样的状态有不一样的操做行为。ide
例如,水在固体、液体、气体是三种状态,可是展示在咱们面前的确实不一样的感受。经过改变水的状态,就能够更改它的展示方式。this
应用场景spa
1 当一个对象的行为,取决于它的状态时code
2 当类结构中存在大量的分支,而且每一个分支内部的动做抽象相同,能够当作一种状态来执行时。htm
Context 环境角色,里面包含状态对象对象
class Context{ private State state; public void setState(State state) { this.state = state; } public void operation(){ state.operation(); } }
State 状态的抽象接口blog
interface State{ public void operation(); }
ConcreteState 具体的状态角色接口
class ConcreteState1 implements State{ public void operation(){ System.out.println("state1 operation"); } } class ConcreteState2 implements State{ public void operation(){ System.out.println("state2 operation"); } } class ConcreteState3 implements State{ public void operation(){ System.out.println("state3 operation"); } }
所有代码get
1 package com.xingoo.test.design.state; 2 class Context{ 3 private State state; 4 public void setState(State state) { 5 this.state = state; 6 } 7 public void operation(){ 8 state.operation(); 9 } 10 } 11 interface State{ 12 public void operation(); 13 } 14 class ConcreteState1 implements State{ 15 public void operation(){ 16 System.out.println("state1 operation"); 17 } 18 } 19 class ConcreteState2 implements State{ 20 public void operation(){ 21 System.out.println("state2 operation"); 22 } 23 } 24 class ConcreteState3 implements State{ 25 public void operation(){ 26 System.out.println("state3 operation"); 27 } 28 } 29 public class Client { 30 public static void main(String[] args) { 31 Context ctx = new Context(); 32 State state1 = new ConcreteState1(); 33 State state2 = new ConcreteState2(); 34 State state3 = new ConcreteState3(); 35 36 ctx.setState(state1); 37 ctx.operation(); 38 39 ctx.setState(state2); 40 ctx.operation(); 41 42 ctx.setState(state3); 43 ctx.operation(); 44 } 45 }
运行结果
state1 operation state2 operation state3 operation