State Pattern
State Pattern에 대해 설명하는 페이지입니다.
State Pattern
Tags
Design Pattern, Java
1. Introduction
- Purpose
- Ties object circumstances to its behavior, allowing the object to behave in different ways based upon its internal state.
- Use When
- The behavior of an object should be influenced by its state.
- Complex conditions tie object behavior to its state.
- Transitions between states need to be explicit.
2. Characteristics
- Encapsulate what varies
- Put each state’s behavior in its own class, then every state just implements its own actions
- The client object can delegate to the state object that represents the current state
- Favor composition over inheritance
- Get rid of all of our conditional code and instead delegate to the state object to do the work for us.
- Localized the behavior of each state into its own class
- Removed all the troublesome conditional statements that would have been difficult to maintain
- Closed each state for modification, and yet left the client open to extension by adding new state classe
- The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
- An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
- Pros and Cons
- Pros
- Puts all behavior associated with a state into one object
- Allows state transition logic to be incorporated into a state object rather than in a monolithic if or switch statement
- Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes
- Cons
- Increased number of objects
- Pros
3. How to Use (Example)
-
State
java1public interface State { 2 public void work(); 3} -
Concrete State
java1public class WorkingState implements State { 2 public Person person; 3 4 public WorkingState(Person person) { 5 this.person = person; 6 } 7 8 @Override 9 public void work() { 10 System.out.println("I'm working!"); 11 person.setState(person.getRestingState()); 12 } 13}java1public class RestingState implements State { 2 public Person person; 3 4 public RestingState(Person person) { 5 this.person = person; 6 } 7 8 @Override 9 public void work() { 10 System.out.println("I'm resting!"); 11 person.setState(person.getWorkingState()); 12 } 13} -
Client
java1public class Person { 2 private State workingState; 3 private State restingState; 4 private State state = workingState; 5 6 public Person() { 7 workingState = new WorkingState(this); 8 restingState = new RestingState(this); 9 } 10 11 public void setState(State state) { 12 this.state = state; 13 } 14 15 public State getWorkingState() { 16 return workingState; 17 } 18 19 public State getRestingState() { 20 return restingState; 21 } 22 23 public void work() { 24 state.work(); 25 } 26}
