头图

The definition of the state pattern is to allow an object to change its behavior by changing its state.

There are the following roles in the status mode

  • Context class: used to record state, modify state, call behavior, etc.
  • Abstract state class: the parent class of all classes used to represent the same class of state, and defines a behavioral interface
  • Concrete state classes: concrete implementations of different states

The following is an implementation of a printer's behavior using the state pattern.

context class

 public class PrinterContext {
    private PrinterState state;

    public PrinterContext(PrinterState state) {
        this.state = state;
    }

    public PrinterState getState() {
        return state;
    }

    public void setState(PrinterState state) {
        this.state = state;
    }

    public void handle(){
        state.handle(this);
    }
}

abstract state class

 public interface PrinterState {
    void handle(PrinterContext context);
}

Concrete state class

 public class OccupyState implements PrinterState {
    @Override
    public void handle(PrinterContext context) {
        System.out.println("打印机正在被占用....");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println("打印结束,转为空闲模式");
            context.setState(new IdleState());
        }
    }
}
 public class IdleState implements PrinterState {

    @Override
    public void handle(PrinterContext context) {
        System.out.println("打印机空闲中.....");
    }
}

test class

 public class StateTest {
    @Test
    public void test(){
        PrinterState occupyState = new OccupyState();
        PrinterContext context = new PrinterContext(occupyState);
        context.handle();
    }
}
=====结果=====
打印机正在被占用....
打印结束,转为空闲模式

The state pattern is very similar to the strategy pattern, and it is easy to see some differences between the two with the following two sequence diagrams.
Original link


eacape
211 声望8 粉丝

JAVA 攻城狮


« 上一篇
策略模式
下一篇 »
备忘录模式