首页 > 其他 > 详细

第十六章 状态模式

时间:2016-04-04 22:54:06      阅读:346      评论:0      收藏:0      [点我收藏+]

好处:将与特定状态相关的行为局部化,并将不同状态的行为分割开来。

当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式。

/**
 * Created by hero on 16-4-4.
 */
public abstract class State {
    public abstract void handle(Context context);
}
/**
 * Created by hero on 16-4-4.
 */
public class ConcreteStateA extends State {
    @Override
    public void handle(Context context) {
        System.out.println("state a");
        context.setState(new ConcreteStateB());
        context.request();
    }
}
/**
 * Created by hero on 16-4-4.
 */
public class ConcreteStateB extends State {
    @Override
    public void handle(Context context) {
        System.out.println("state b--->the end state");
        //context.setState(new ConcreteStateA());
    }
}
/**
 * Created by hero on 16-4-4.
 */
public class Context {
    private State state;

    public void request() {
        state.handle(this);
    }

    public Context(State state) {
        this.state = state;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }
}
public class Main {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStateA());
        context.request();
    }
}

 

第十六章 状态模式

原文:http://www.cnblogs.com/littlehoom/p/5353122.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!