设计模式开始--状态模式

状态模式

一、定义:

当一个对象内在状态改变时允许改变行为,实现状态的改变

二、作用

主要解决的是当一个状态转换的条件表达式过于复杂的时候,把状态的判断转移到不同状态的一系列类中,把复杂的判断简单化

三、类图:

四、实现

1.work类 用于实现转换状态,状态判断,运行对应状态的程序 同时也是用户调用的接口

public class Work {
    State state;
    public Work()
    {
        this.state = new Fornoon();
    }
    private int hour;
    public int getHour()
    {
        return this.hour;
    }
    public void setHour(int hour)
    {
        this.hour = hour;
    }
    public void doWork()
    {
        this.state.doWork(this);
    }
    public void setState(State state)
    {
        this.state = state;
    }
}
View Code

2.state类 实际运行的情况,调用work的状态切换

public abstract class State {
    public abstract void doWork(Work work);
}
View Code

3.state的实现类

public class Afternoon extends State {
    @Override
    public void doWork(Work work) {
        if(work.getHour() > 12)
        {
            System.out.println("in the afternoon");
        }
        else
        {
            work.setState(new Fornoon());
            work.doWork();
        }
    }
}
public class Fornoon extends State {

    @Override
    public void doWork(Work work) {
        if(work.getHour() < 12)
        {
            System.out.println("in the morning");
        }
        else
        {
            work.setState(new Afternoon());
            work.doWork();
        }
    }

}
View Code

4.客户类 测试类

public class Client {
    public static void main(String[] args)
    {
        Work work = new Work();
        work.setHour(14);
        work.doWork();
        work.setHour(14);
        work.doWork();
    }
}
View Code

 

posted on 2015-03-31 16:57  zhouzhou0615  阅读(104)  评论(0编辑  收藏  举报

导航