상태패턴 (1)

Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼 State 패턴은 Behavioral 패턴에 속한다. 

 

State Pattern Structure

 

패턴의 목적 ( Intent ) : 

Allow an object to alter its behavior when its internal state changes.The object will appear to change its class.

State 패턴의 목적은 내부 상태의 변화에 따라 객체의 행위를 변경할 수 있도록 하기 위함이다.


 위 다이어그램을 예제로 들면 TCPConnection은 TCPState객체를 가지고 있는 클래스다. 그리고 이 TCPState객체는 상태를 나타내는 클래스로 크게 세가지 상태로 나뉘는데 ( Established, Listen, Closed ) 이 상태의 변화에 따라 TCPConnection에서 호출하는 open()메소드가 TCPEstablished객체의 open()이 될 수도 있고 TCPListen나  TCPClosed 객체의 open()이 될 수도 있다.  

 

유용성 ( Applicability ) :

· An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.

객체의 행위가 상태에 따라 동적으로 변해야 할 때
· Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a
separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.

어떤 작업이 객체의 상태에 의존하는 여러개의 큰 조건문을 가지고 있다고 해보자( 쉽게 말해 객체의 상태를 나타내는 상수값이 조건문의 조건절에 들어가 있다고 생각해보자 ). 일반적으로 상태라는 것은 최소 하나 이상의 상수값에 의해 표현이 될 수 있는데, 이를 상태패턴을 이용하여 클래스에 담아버리는 것이다. 즉, 객체의 상태값을 나타내는 객체를 만들어 버리는 것이다.

 

등장 인물 :
· Context (TCPConnection)
o defines the interface of interest to clients.
o maintains an instance of a Concrete State subclass that defines the current state.

· State (TCPState)
o defines an interface for encapsulating the behavior associated with a particular state of the Context. 

 

· ConcreteState subclasses (TCPEstablished, TCPListen, TCPClosed)
o each subclass implements a behavior associated with a state of the Context.

 

원리 ( Collaborations ) :

· Context delegates state-specific requests to the current ConcreteState object.

Context는 상태에 따른 메소드 호출을 ConcreteState객체에 위임한다.
· A context may pass itself as an argument to the State object handling the request. This lets the State object access the context if necessary.

상태객체가 Context를 필요로한다면 Context객체는 자신을 argument로 넘겨주어 상태객체에서 접근할 수 있도록 할 수 있다.
· Context is the primary interface for clients. Clients can configure a context with State objects. Once a context is configured, its clients don't have to deal with the State objects directly.

클라이언트는 상태객체를 이용해서 context를 설정할 수 있는데 한번 설정하면 그 다음부터는 상태객체에 직접적으로 접근할 필요가 없다.
· Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances.

Context 또는 ConcreteState의 하위 클래스들은 상태의 순서를 결정할 수 있다.


패턴 사용의 장단점 ( Consequences ):
1. It localizes state-specific behavior and partitions behavior for different states.The State pattern puts all behavior associated with a particular state into one object. Because all state-specific code lives in a State subclass, new states and transitions can be added easily by defining new subclasses.
An alternative is to use data values to define internal states and have Context operations check the data explicitly. But then we'd have look-alike conditional or case statements scattered throughout Context's implementation. Adding a new state could require changing several operations, which complicates maintenance.

The State pattern avoids this problem but might introduce another, because the pattern distributes behavior for different states across several State subclasses. This increases the number of classes and is less compact than a single class. But such distribution is actually good if there are many states, which would otherwise necessitate large conditional statements.
Like long procedures, large conditional statements are undesirable.They're monolithic and tend to make the code less explicit, which in turn makes them difficult to modify and extend. The State pattern offers a better way to structure state-specific code. The logic that determines the state transitions doesn't reside in monolithic if or switch statements but instead is partitioned between the State  subclasses. Encapsulating each state transition and action in a class elevates the idea of an execution state to full object status. That imposes structure on the code and makes its intent clearer. 

 

2. It makes state transitions explicit.When an object defines its current state solely in terms of internal data values, its state transitions have no explicit representation;they only show up as assignments to some variables. Introducing separate objects for different states makes the transitions more explicit. Also, State objects can protect the Context from inconsistent internal states, because state transitions are atomic from the Context's perspective—they happen by rebinding one variable (the Context's State object variable), not several. 

 

3. State objects can be shared.If State objects have no instance variables—that is, the state they represent is encoded entirely in their type—then contexts can sharea State object. When states are shared in this way, they are essentially flyweights (see Flyweight) with nointrinsic state, only behavior.


관련 패턴들 : 

The Flyweight pattern explains when and how State objects can be shared.

Flyweight 패턴은 언제 어떻게 상태 객체들이 공유되는지 설명해준다.

State objects are often Singletons.

상태 객체들은 대부분 싱글턴이다.



추가 정보 :

  • State objects are often Singletons.
  • Flyweight explains when and how State objects can be shared.
  • Interpreter can use State to define parsing contexts.
  • Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
  • The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object's behavior to change along with its state, while Bridge's intent is to decouple an abstraction from its implementation so that the two can vary independently.
  • The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the "context" object causes it to select from its "palette" of Strategy objects.

 

출처 : http://sourcemaking.com/design_patterns/state

         Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )