java设计模式,状态模式

来源:互联网 发布:叶友根字体下载mac 编辑:程序博客网 时间:2024/05/29 02:54
package com.dasenlin.designmodel;/** * 状态模式(State) * 核心思想就是:当对象的状态改变时,同时改变其行为, * 很好理解!就拿QQ来说,有几种状态,在线、隐身、忙碌等, * 每个状态对应不同的操作,而且你的好友也能看到你的状态,所以, * 状态模式就两点:1、可以通过改变状态来获得不同的行为。2、你的好友能同时看到你的变化。看图: * State类是个状态类,Context类可以实现切换,我们来看看代码: * @author Administrator * */public class State {    private String value;    public String getValue() {        return value;    }    public void setValue(String value) {        this.value = value;    }    public void method1(){        System.out.println("this is first opt");    }    public void method2(){        System.out.println("this is second opt");    }    /**     * 测试     * @param args     */    public static void main(String[] args) {        State state = new State();        Content content = new Content(state);        state.setValue("state1");        content.method();        state.setValue("state2");        content.method();    }}class Content{    private State state;    public State getState() {        return state;    }    public void setState(State state) {        this.state = state;    }    public Content(State state) {        super();        this.state = state;    }    public void method(){        if(state.getValue().equals("state1")){            state.method1();        }else if(state.getValue().equals("state2")){            state.method2();        }    }}
0 0
原创粉丝点击