注:本文为译文,原文出处 java-design-patterns-in-stories
状态模式主要用于在运行时改变状态.
状态模式故事
人们生活在不同的经济条件下. 他们或许富有或许贫穷. 这两种状态 - 富有与贫穷 - 可以随时间相互转换. 例子背后的启示: 人们通常在贫穷时候工作的更加努力, 而富有时则更乐于享乐. 他们的行为依赖于他们的生活状态. 这个状态可以基于他们的行为被改变, 不然, 这个社会就不公平了.
状态模式类图
下面是类图. 你可以拿 策略模式 来进行比较, 以便能更好的理解两者的不同.
状态模式Java代码
下面的Java代码体现了状态模式是如何进行工作的.
状态类.
package com.programcreek.designpatterns.state; interface State { public void saySomething(StateContext sc); } class Rich implements State{ @Override public void saySomething(StateContext sc) { System.out.println("I'm rick currently, and play a lot."); sc.changeState(new Poor()); } } class Poor implements State{ @Override public void saySomething(StateContext sc) { System.out.println("I'm poor currently, and spend much time working."); sc.changeState(new Rich()); } }
状态上下文类.
package com.programcreek.designpatterns.state; public class StateContext { private State currentState; public StateContext(){ currentState = new Poor(); } public void changeState(State newState){ this.currentState = newState; } public void saySomething(){ this.currentState.saySomething(this); } }
测试类.
import com.programcreek.designpatterns.*; public class Main { public static void main(String args[]){ StateContext sc = new StateContext(); sc.saySomething(); sc.saySomething(); sc.saySomething(); sc.saySomething(); } }
输出结果:
I'm poor currently, and spend much time working. I'm rick currently, and play a lot. I'm poor currently, and spend much time working. I'm rick currently, and play a lot.
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得
100積分直接送
付費(fèi)專(zhuān)欄免費(fèi)學(xué)
大額優(yōu)惠券免費(fèi)領(lǐng)