狀態(state)模式:狀態模式的意圖是,容許一個對象在其內部狀改變時改變它的行爲。看起來就像是改變了它的類同樣。主要解決的是當控制一個對象狀態轉換的條件表達式過於複雜時的狀況。把狀態的判斷邏輯轉移到表示不一樣的一系列類當中,能夠把複雜的邏輯判斷簡單化。java
角色:設計模式
三、場景(Context)角色:定義客戶端所感興趣的接口,而且保留一個具體狀態類的實例。這個具體狀態類的實例給出此環境對象現有的狀態。ide
總結:感受狀態模式就是將原本在外部進行的狀態轉移,挪到了具體狀態類內部進行。它經過具體狀態類(Concrete State)持有場景的引用,改變場景(Context)的狀態,從而不須要在外部控制狀態的變化。學習
package com.perfecking.base; public class StateModeDemo { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub LightManager lightManager = new LightManager(); lightManager.setState(new GreenLight()); lightManager.shine(); } } interface State{ public void change(LightManager light); } class LightManager{ State state = null; public void setState(State state){ this.state = state; } public void shine(){ while(true){ state.change(this); } } } class GreenLight implements State{ private static final int SLEEP_TIME = 2000; @Override public void change(LightManager light) { // TODO Auto-generated method stub System.out.println("Green Light Is Shining!請通行~~"); try { Thread.sleep(SLEEP_TIME); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } light.setState(new YellowLight()); } } class RedLight implements State{ private final static int SLEEP_TIME = 3000; @Override public void change(LightManager light) { // TODO Auto-generated method stub System.out.println("Red Light Is Shining!禁止通行~"); try { Thread.sleep(SLEEP_TIME); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } light.setState(new GreenLight()); } } class YellowLight implements State{ private final static int SLEEP_TIME = 1000; @Override public void change(LightManager light) { // TODO Auto-generated method stub System.out.println("Yellow Light Is Shining!禁止通行~"); try { Thread.sleep(SLEEP_TIME); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } light.setState(new RedLight()); } }
參考:java設計模式學習this