定义
状态模式是一种行为计划模式,它允许对象在内部状态改变时改变其行为,看起来好像这个对象改变了它的类。这种模式常用于处置惩罚对象在差别状态下的差别行为,使得代码更加结构化和易于维护。
在状态模式中,有以下几个关键角色:
- Context(上下文):持有一个State对象的引用,通常会有一个方法来设置或获取当前状态。
- State(状态):定义了状态接口,声明了全部可能的操纵。
- ConcreteState(具体状态):实现了State接口,提供了具体的行为。
示例代码
- public interface VendingMachineState {
- void insertCoin();
- void ejectCoin();
- void turnCrank();
- void dispense();
- }
复制代码- public class NoMoneyState implements VendingMachineState {
- private VendingMachine vendingMachine;
- public NoMoneyState(VendingMachine vendingMachine) {
- this.vendingMachine = vendingMachine;
- }
- @Override
- public void insertCoin() {
- System.out.println("Coin inserted, new state is HasMoney");
- vendingMachine.setState(vendingMachine.getHasMoneyState());
- }
- @Override
- public void ejectCoin() {}
- @Override
- public void turnCrank() {}
- @Override
- public void dispense() {}
- }
复制代码- public class HasMoneyState implements VendingMachineState {
- private VendingMachine vendingMachine;
- public HasMoneyState(VendingMachine vendingMachine) {
- this.vendingMachine = vendingMachine;
- }
- @Override
- public void insertCoin() {
- System.out.println("Machine is already in HasMoney state, coin will be added to credit");
- }
- @Override
- public void ejectCoin() {
- }
- @Override
- public void turnCrank() {
- System.out.println("Machine is already in HasMoney state, turnCrank is not allowed");
- }
- @Override
- public void dispense() {
- }
- }
复制代码- public class VendingMachine {
- private VendingMachineState state;
- public VendingMachine() {
- this.state = new NoMoneyState(this);
- }
- public VendingMachineState getState() {
- return state;
- }
- public void setState(VendingMachineState state) {
- this.state = state;
- }
- public void insertCoin() {
- state.insertCoin();
- }
- public void ejectCoin() {
- state.ejectCoin();
- }
- public void turnCrank() {
- state.turnCrank();
- }
- public void dispense() {
- state.dispense();
- }
- public VendingMachineState getHasMoneyState() {
- return new HasMoneyState(this);
- }
- }
复制代码- public class StateTest {
- @Test
- public void test() {
- VendingMachine machine = new VendingMachine();
- machine.insertCoin(); // 输出 "Coin inserted, new state is HasMoney"
- machine.turnCrank(); // 根据HasMoneyState的行为执行
- }
- }
复制代码 源代码地址
https://gitee.com/youxiaxiaomage/java-practices/tree/master/yxxmg-gof-sample/src/main/java/com/yxxmg/gof/behavior/state
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |