State 状态模式

来源:互联网 发布:简单的c语言程序50行 编辑:程序博客网 时间:2024/05/16 14:43
package com.lonton.designpatterns;interface State{public void saySomething(StateContext stateContext);}class Poor implements State{@Overridepublic void saySomething(StateContext sc){// TODO Auto-generated method stubSystem.out.println("I'm poor currently, and spend much time working.");sc.changeState(new Rich());}}class Rich implements State{@Overridepublic void saySomething(StateContext sc){// TODO Auto-generated method stubSystem.out.println("I'm rick currently, and play a lot.");sc.changeState(new Poor());}}class StateContext{private State curState;public StateContext(){curState = new Poor();}public void changeState(State state){curState = state;}public void saySomething(){curState.saySomething(this);}}public class StateTest{public static void main(String[] args){StateContext sc = new StateContext();sc.saySomething();sc.saySomething();sc.saySomething();sc.saySomething();}}

0 0
原创粉丝点击