Quantcast
Channel: Free practice test , mock test, driving test, interview questions » design patterns
Viewing all articles
Browse latest Browse all 10

State Design Pattern

$
0
0

Problem

When an object has different internal states, how can we implement the states without complicated boolean logic inside the class?

Solution

The answer is the state design pattern. In this pattern, the context object contains a state object, which represents the current state that the context object is in. It does this by implementing all the class methods of the context object. Whenever a context object receives a method call, it passes that call on to its state to execute the functionality. The context object changes the state object as needed to correctly relate to its internal state.

Consequences

Encapsulates specific functionality for specific states in its own class

Provides an easy way to extend the functionality of a context class. Just add more states.

State objects can be shared in certain cases to increase reuse.


Viewing all articles
Browse latest Browse all 10

Trending Articles