Javatpoint Logo
Javatpoint Logo

State Pattern

A State Pattern says that "the class behavior changes based on its state". In State Pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

The State Pattern is also known as Objects for States.


Benefits:

  • It keeps the state-specific behavior.
  • It makes any state transitions explicit.

Usage:

  • When the behavior of object depends on its state and it must be able to change its behavior at runtime according to the new state.
  • It is used when the operations have large, multipart conditional statements that depend on the state of an object.

UML for State Pattern:

State Pattern

Implementation of State Pattern:

Step 1:

Create a Connection interface that will provide the connection to the Controller class.

Step 2:

Create an Accounting class that will implement to the Connection interface.

Step 3:

Create a Sales class that will implement to the Connection interface.

Step 4:

Create a Sales class that will implement to the Connection interface.

Step 5:

Create a Management class that will implement to the Connection interface.

Step 6:

Create a Controller class that will use the Connection interface for connecting with different types of connection.

Step 7:

Create a StatePatternDemo class.

Output:

State Pattern






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA