还为那些设计模式烦恼吗-状态模式

2018-03-10  本文已影响3人  Jenchar

定义

当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类

public interface TvState {
    public void next();
    public void pre();
    public void up();
    public void down();
}
package com.qc.state;

public class PowerOffState implements TvState {

    @Override
    public void next() {
        // TODO Auto-generated method stub

    }

    @Override
    public void pre() {
        // TODO Auto-generated method stub

    }

    @Override
    public void up() {
        // TODO Auto-generated method stub

    }

    @Override
    public void down() {
        // TODO Auto-generated method stub

    }

}

package com.qc.state;

public class PowerOnState implements TvState {

    @Override
    public void next() {
        // TODO Auto-generated method stub
        System.out.println("下一首");
    }

    @Override
    public void pre() {
        // TODO Auto-generated method stub
        System.out.println("上一首");
    }

    @Override
    public void up() {
        // TODO Auto-generated method stub
        System.out.println("上");
    }

    @Override
    public void down() {
        // TODO Auto-generated method stub
        System.out.println("下");
    }

}
package com.qc.state;

public interface PowerController {
    public void powerOn();
    public void powerOff();
}

package com.qc.state;

public class Tv implements PowerController {
    TvState mTvState;

    @Override
    public void powerOn() {
        // TODO Auto-generated method stub
        setTvState(new PowerOnState());
    }

    @Override
    public void powerOff() {
        // TODO Auto-generated method stub
        setTvState(new PowerOffState());
    }

    public void setTvState(TvState mTvState) {
        this.mTvState = mTvState;
    }

    public void next() {
        mTvState.next();
    }

    public void pre() {
        mTvState.pre();
    }

    public void up() {
        mTvState.up();
    }

    public void down() {
        mTvState.down();
    }

}

package com.qc.state;

public class Client {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Tv mTv = new Tv();
        mTv.powerOn();
        mTv.next();
        mTv.pre();
        mTv.up();
        mTv.down();
    }

}

使用

1、一个对象的行为取决于它的状态。并且它必须在运行时根据状态改变它的行为。
2、代码中包含大量与对象状态有关的条件语句,例如,一个操作中含有庞大的多分支语句(if-else或switch-case),且这些分支依赖于该对象的状态。

上一篇下一篇

猜你喜欢

热点阅读