STATE (Object Behavioral)
Purpose
Ties object circumstances to its behavior, allowing the object
to behave in different ways based upon its internal state.
Use When
1 The behavior of an object should be influenced by its state.
2 Complex conditions tie object behavior to its state.
3 Transitions between states need to be explicit.
Example
An email object can have various states, all of which will
change how the object handles different functions. If the state
is “not sent” then the call to send() is going to send the message
while a call to recallMessage() will either throw an error or do
nothing. However, if the state is “sent” then the call to send()
would either throw an error or do nothing while the call to
recallMessage() would attempt to send a recall notification
to recipients. To avoid conditional statements in most or all
methods there would be multiple state objects that handle the
implementation with respect to their particular state. The calls
within the Email object would then be delegated down to the
appropriate state object for handling.
- package javaPattern.state;
- public interface State {
- public void handle(Context context);
- }
- class ConcreteStateA implements State{
- @Override
- public void handle(Context context) {
- //在A中设置B状态
- context.setState(new ConcreteStateB());
- }
- }
- class ConcreteStateB implements State{
- @Override
- public void handle(Context context) {
- //在B中设置A状态
- context.setState(new ConcreteStateA());
- }
- }
- class Context {
- private State state;
- public State getState() {
- return state;
- }
- public void setState(State state) {
- this.state = state;
- System.out.println("当前设置的状态是"+state.getClass().getName());
- }
- public Context(State state) {
- this.state = state;
- }
- public void request(){
- this.state.handle(this);
- }
- public static void main(String[] args) {
- Context context = new Context(new ConcreteStateA());
- context.request();
- }
- }