State Pattern

A monolithic object's behavior is a function of its state, and it must change its behavior at run-time depending on that state. The State Pattern is a solution to the problem of how to make behavior depend on state.

Intent

  • Allow an object to alter its behavior when its internal state changes.

Implementation

Class Diagram of State Pattern

Let's use the state of an mp3 player to give an example. First we set up a Context for the mp3 player.

// MP3PlayerContext.java
public class MP3PlayerContext {
    private State state;

    public MP3PlayerContext() {
        this.state = new StandbyState();
    }

    public void press() {
        state.pressPlay(this);
    }

    public void setState(State state) {
        this.state = state;
    }

    public void getState() {
        System.out.println(state.getState());
    }
}

Here is our State interface, on which the pressPlay() imitates the play botton.

// State.java
public interface State {

    void pressPlay(MP3PlayerContext context);
    String getState();
}

Now, we create states for StandbyState and PlayingState.

// PlayingState.java
public class PlayingState implements State {

    public void pressPlay(MP3PlayerContext context) {
        context.setState(new StandbyState());
    }

    @Override
    public String getState() {
        return "Playing...";
    }
}
// StandbyState.java
public class StandbyState implements State {

    public void pressPlay(MP3PlayerContext context) {
        context.setState(new PlayingState());
    }

    @Override
    public String getState() {
        return "Stand By...";
    }
}

Our client presses the button to turn on the mp3, and then presses again to turn it off.

// ClientDemo.java
public class ClientDemo {

    public static void main(String[] args) {

        MP3PlayerContext mp3Player = new MP3PlayerContext();
        mp3Player.press();
        mp3Player.getState();
        mp3Player.press();
        mp3Player.getState();
    }
}

Output:

Playing...
Stand By...

More

State Pattern vs Finite State Machine

According to this stackoverflow post, the State Pattern is more decentralized while Finite State Machine is more monolithic:

The way I describe this difference to my colleagues is that state patterns are a more decentralized implementation of many stand alone encapsulated states whereas state machines are more monolithic. The monolithic nature of state machines means that a single state will be harder to reuse in a different machine and that it is harder to break a state machine up into multiple compilation units. On the other hand this monolithic design allows far better optimization of state machines and allows many implementations to represent all transition information in one place in a table...

Notice that in State Pattern, switching states requires an allocation, which actually kills speed. Use the State Pattern in cases where speed is a not an issue.

Reference

Code Project
DZone
Hackjustu Dojo (my blog)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末拆魏,一起剝皮案震驚了整個濱河市序目,隨后出現(xiàn)的幾起案子莹汤,更是在濱河造成了極大的恐慌菱阵,老刑警劉巖佑惠,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異敏弃,居然都是意外死亡笛辟,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門宫患,熙熙樓的掌柜王于貴愁眉苦臉地迎上來刊懈,“玉大人,你說我怎么就攤上這事⌒檠矗” “怎么了匾浪?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長卷哩。 經(jīng)常有香客問我蛋辈,道長,這世上最難降的妖魔是什么将谊? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任冷溶,我火速辦了婚禮,結(jié)果婚禮上尊浓,老公的妹妹穿的比我還像新娘逞频。我一直安慰自己,他們只是感情好眠砾,可當(dāng)我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布虏劲。 她就那樣靜靜地躺著,像睡著了一般褒颈。 火紅的嫁衣襯著肌膚如雪柒巫。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天谷丸,我揣著相機與錄音堡掏,去河邊找鬼。 笑死刨疼,一個胖子當(dāng)著我的面吹牛泉唁,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播揩慕,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼亭畜,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了迎卤?” 一聲冷哼從身側(cè)響起拴鸵,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蜗搔,沒想到半個月后劲藐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡樟凄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年聘芜,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缝龄。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡汰现,死狀恐怖挂谍,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情服鹅,我是刑警寧澤凳兵,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站企软,受9級特大地震影響庐扫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜仗哨,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一形庭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧厌漂,春花似錦萨醒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至旨椒,卻和暖如春晓褪,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背综慎。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工涣仿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人示惊。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓好港,卻偏偏與公主長得像,于是被迫代替她去往敵國和親米罚。 傳聞我的和親對象是個殘疾皇子钧汹,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,489評論 0 23
  • 上一章:婉豆說(03) 8.其實沒那么想念 玉蘭樹的葉子仍綠著,漳江上的漁船在冬季里也住著人录择,曾伏在沈哲肩頭崭孤,走過...
    喬三的馬甲閱讀 318評論 0 2
  • 《精疲力盡》 二 大學(xué)初體驗 高考前的那段日子,對于大多數(shù)人來說都很難忘糊肠。對于我來說,用復(fù)讀兩年...
    精疲力盡的小七閱讀 475評論 0 0
  • 28 ProGuard混淆介紹 28.1ProGuard簡介 Java源代碼(.java文件)通常被編譯為字節(jié)碼(...
    xjbclz閱讀 235評論 0 0
  • 美食品鑒大師蔡瀾在著作《暖食》中對蛋炒飯有這樣一段絕妙的表述: “炒飯的最高境界在于炒得蛋包住米飯遗锣,呈金黃货裹,才能叫...
    ShannaShau閱讀 332評論 0 0