在状态模式(State Pattern)中,类的行为是基于它的状态改变的。当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
表明状态, 实体类是根据状态的变化而发生响应行为的变化的.
/** * 状态抽象定义 */ public interface State { void onEnterState(); void observe(); }
状态的一种实现.
/** * 生气状态 */ public class AngryState implements State { private Mammoth mammoth; public AngryState(Mammoth mammoth) { this.mammoth = mammoth; } @Override public void observe() { System.out.printf("%s 处于暴躁状态!\n", mammoth); } @Override public void onEnterState() { System.out.printf("%s 开始生气了!\n", mammoth); } }
状态的一种实现.
/** * 平静状态 */ public class PeacefulState implements State { private Mammoth mammoth; public PeacefulState(Mammoth mammoth) { this.mammoth = mammoth; } @Override public void observe() { System.out.printf("%s 现在很平静.\n", mammoth); } @Override public void onEnterState() { System.out.printf("%s 开始冷静下来了.\n", mammoth); } }
本类是状态State的持有者
/** * 猛犸大象 */ 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 observe() { this.state.observe(); } @Override public String toString() { return "猛犸大象"; } }
用于模拟场景以及运行代码
public class Main { public static void main(String[] args) { Mammoth mammoth = new Mammoth(); // 看看大象现在是什么状态 mammoth.observe(); // 过了一会儿 mammoth.timePasses(); // 看看大象现在是什么状态 mammoth.observe(); // 过了一会儿 mammoth.timePasses(); // 看看大象现在是什么状态 mammoth.observe(); } }
运行结果如下:
如对本文有疑问, 点击进行留言回复!!
springcloud中feign调用处理mybatis-plus Ipage反序列化问题。
Flume 史上最全面的大数据学习第十篇(一) 别再说不知道flume是什么了
网友评论