State pattern
The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern’s interface.
The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability —Wikipedia
Structure
Example
public class Main {
public static void main(String[] args) {
new MM().cry();
}
}
class MM {
String name;
MMState state = new MMHappyState();
public void smile() {
state.smile();
}
public void cry() {
state.cry();
}
public void say() {
state.say();
}
}
class MMHappyState extends MMState {
@Override
void smile() {
System.out.println("happy smile");
}
@Override
void cry() {
System.out.println("happy cry");
}
@Override
void say() {
System.out.println("happy say");
}
}
class MMNervousState extends MMState {
@Override
void smile() {
System.out.println("nervous smile");
}
@Override
void cry() {
System.out.println("nervous cry");
}
@Override
void say() {
System.out.println("nervous say");
}
}
class MMSadState extends MMState {
@Override
void smile() {
System.out.println("sad smile");
}
@Override
void cry() {
System.out.println("sad cry");
}
@Override
void say() {
System.out.println("sad say");
}
}
abstract class MMState {
abstract void smile();
abstract void cry();
abstract void say();
}
Summary
- 一个类有很多个动作,每个动作根据不同的状态,有不同的反应
- 适用于操作不扩展,但是有多种State并且可能会扩展的情况
- state machine和state desing pattern 是不同的东西