前言:【模式總覽】——————————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