標籤:java設計模式 state
轉載請註明出處:http://blog.csdn.net/l1028386804/article/details/45600711
一、概述
定義對象間的一種一對多的依賴關係,當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並被自動更新。
二、適用性
1.一個對象的行為取決於它的狀態,並且它必須在運行時刻根據狀態改變它的行為。
2.一個操作中含有龐大的多分支的條件陳述式,且這些分支依賴於該對象的狀態。 這個狀態通常用一個或多個枚舉常量表示。 通常,有多個操作包含這一相同的條件結構。 State模式將每一個條件分支放入一個獨立的類中。 這使得你可以根據對象自身的情況將對象的狀態作為一個對象,這一對象可以不依賴於其他對象而獨立變化。
三、適用性
1.Context 定義客戶感興趣的介面。 維護一個ConcreteState子類的執行個體,這個執行個體定義目前狀態。
2.State 定義一個介面以封裝與Context的一個特定狀態相關的行為。
3.ConcreteStatesubclasses 每一子類實現一個與Context的一個狀態相關的行為。
四、類圖
五、樣本
Context
package com.lyz.design.state;/** * Context * @author liuyazhuang * */public class Context { private Weather weather; public void setWeather(Weather weather) { this.weather = weather; } public Weather getWeather() { return this.weather; } public String weatherMessage() { return weather.getWeather(); }}
State
package com.lyz.design.state;/** * State * @author liuyazhuang * */public interface Weather { String getWeather();}
ConcreteStatesubclasses
package com.lyz.design.state;/** * ConcreteStatesubclasses * @author liuyazhuang * */public class Rain implements Weather { public String getWeather() { return "下雨"; }}
package com.lyz.design.state;/** * ConcreteStatesubclasses * @author liuyazhuang * */public class Sunshine implements Weather { public String getWeather() { return "陽光"; }}
Test
package com.lyz.design.state;/** * Test * @author liuyazhuang * */public class Test{ public static void main(String[] args) { Context ctx1 = new Context(); ctx1.setWeather(new Sunshine()); System.out.println(ctx1.weatherMessage()); System.out.println("==============="); Context ctx2 = new Context(); ctx2.setWeather(new Rain()); System.out.println(ctx2.weatherMessage()); }}
result
陽光===============下雨
淺談JAVA設計模式之——狀態模式(State)