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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。