淺談JAVA設計模式之——狀態模式(State)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.