设计模式-对象状态模式

文章通过状态模式展示了猛犸象在和平与愤怒两种状态之间的切换。猛犸象类包含一个状态接口,有两个实现类:和平状态和愤怒状态。随着时间的推移,猛犸象的状态会发生变化,其行为也随之改变,类似于有限状态机或策略模式的应用。
摘要由CSDN通过智能技术生成

目的:

允许对象在内部状态改变时改变它的行为。对象看起来好像修改了它的类。状态模式是一种允许对象在内部状态改变时改变它的行为的行为型设计模式。这种模式接近于有限状态机的概念。状态模式可以被理解为策略模式,它能够通过调用在模式接口中定义的方法来切换策略。

程序示例:

当在长毛象的自然栖息地观察长毛象时,似乎它会根据情况来改变自己的行为。它开始可能很平静但是随着时间推移当它检测到威胁时它会对周围的环境感到愤怒和危险。

1.定义状态和不同的实现类

public interface State{
    void onEnterState();
    void observer();
}

@Slf4j
public class PeacefulState implements State{
    private final Mammoth mammoth;

    public PeacefulState(Mammoth mammoth) {
        this.mammoth = mammoth;
    }

    @Override
    public void onEnterState() {
    log.info("{} calms down.", mammoth);
    }

    @Override
    public void observer() {
    log.info("{} is calm and peaceful.", mammoth);
    }
}

@Slf4j
public class AngryState implements State{
    private final Mammoth mammoth;

    public AngryState(Mammoth mammoth) {
        this.mammoth = mammoth;
    }

    @Override
    public void onEnterState() {
        log.info("{} gets angry!", mammoth);
    }

    @Override
    public void observer() {
        log.info("{} is furious!", mammoth);
    }
}

2.定义猛犸象类

public class Mammoth{
    private State state;

    public Mammoth() {
        state=new PeacefulState(this);
    }
	//更改状态
    public void timePasses(){
        if (state.getClass().equals(PeacefulState.class)){
            changeStateTo(new AngryState(this));
        }else {
            changeStateTo(new PeacefulState(this));
        }
    }


    private void changeStateTo(State newState){
        this.state=newState;
        this.state.onEnterState();
    }
	
    public void observer(){
        this.state.observer();
    }

    @Override
    public String toString() {
        return "The Mammoth";
    }
}

3.测试输出

        Mammoth mammoth = new Mammoth();
        mammoth.observer();
        mammoth.timePasses();
        mammoth.observer();
        mammoth.timePasses();
        mammoth.observer();
        /*
        The Mammoth is calm and peaceful.
        The Mammoth gets angry!
        The Mammoth is furious!
        The Mammoth calms down.
        The Mammoth is calm and peaceful.
         */

类图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值