【设计模式】状态模式

使用频率:★★★☆☆

一、什么是状态模式

一个对象的行为根据其内部状态的改变自动变化;

二、补充说明

结构与策略模式基本一致;

与策略模式区别:使用策略模式时,客户端手动选择策略,使用状态模式时,其行为是根据状态是自动切换的。

其内部状态改变时,它的行为(方法)也跟着改变,看起来就像修改了类的方法;

三、角色

抽象状态

具体状态

环境:定义客户端感兴趣的方法,其内部有一个状态接口,运行时可以改变;

客户端

四、例子,JAVA实现

说明:还是策略模式的例子,只不过这个人比较特殊,他喜欢一天走路上班,另一天开车上班...

两种状态:走路上班状态和开车上班状态,运行时可以改变

抽象状态

package com.pichen.dp.behavioralpattern.state;

public interface IState {

    public void execute(StateContext context);
}

具体状态

package com.pichen.dp.behavioralpattern.state;

public class DriveState implements IState{

    @Override
    public void execute(StateContext context) {
        System.out.println("driving。。。");
        context.setState(new WalkState());
    }

}
package com.pichen.dp.behavioralpattern.state;

public class WalkState implements IState{

    @Override
    public void execute(StateContext context) {
        System.out.println("walking。。。");
        context.setState(new DriveState());
    }

}

环境:

package com.pichen.dp.behavioralpattern.state;

public class StateContext {

    IState state;
    
    public StateContext(IState state) {
        this.state = state;
    }

    public void execute(){
        this.state.execute(this);
    }
    /**
     * @return the state
     */
    public IState getState() {
        return state;
    }

    /**
     * @param state the state to set
     */
    public void setState(IState state) {
        this.state = state;
    }
    



}

客户端

package com.pichen.dp.behavioralpattern.state;

public class Main {
    public static void main(String[] args) {
        StateContext stateContext = new StateContext(new WalkState());
        stateContext.execute();
        stateContext.execute();
        stateContext.execute();
        stateContext.execute();
        stateContext.execute();
    }
}

执行结果:用户的上班行为状态在运行时自动切换

walking。。。
driving。。。
walking。。。
driving。。。
walking。。。

 

posted @ 2016-02-25 10:24  风一样的码农  阅读(932)  评论(0编辑  收藏  举报