DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • User-Friendly API Publishing and Testing With Retrofit
  • Composite Design Pattern in Java
  • Iterator Design Pattern In Java
  • The Complete Guide to Stream API and Collectors in Java 8

Trending

  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Build an MCP Server Using Go to Connect AI Agents With Databases
  • Failure Handling Mechanisms in Microservices and Their Importance
  1. DZone
  2. Coding
  3. Languages
  4. State Design Pattern in Java

State Design Pattern in Java

The state pattern in Java is a behavioural software design pattern that allows an object to alter its behaviour when its internal state changes.

By 
Mahipal Nehra user avatar
Mahipal Nehra
·
Jun. 05, 20 · Analysis
Likes (5)
Comment
Save
Tweet
Share
14.2K Views

Join the DZone community and get the full member experience.

Join For Free

State Design Pattern in Java is a software design pattern that allows an object to change its behavior when the internal state of that object changes. The state design pattern is generally used in cases where an object depends on its state and its behavior must be changed during run time depending on its internal state. The state design pattern is one of the many behavioral design patterns and therefore characterizes control flow between objects that is difficult to follow at run time. State Encapsulation is an excellent way to manage change in software. In this article, we will discuss the key aspects of state design pattern motivation, describe what it is, mention the key participants used in implementing it and also use a code example to demonstrate its usage.

What is the State Design Pattern? (State Design Pattern Real World Example)

In computer networks, TCP (Transmission Control Protocol) is a standard that defines how a connection is established and maintained through which the applications can exchange data. A TCP connection object can be in the following states:

  • 1. Established State
  • 2. Listening State
  • 3. Closed State

A TCP (Transmission Control Protocol) connection object can respond to requests based on its current state. The state design pattern is an ideal way to implement such scenarios, it can describe how TCP connection can exhibit different behavior in each state. Normally, the approach is to introduce an abstract class called the TCPState to represent the states of the network connection. The TCPState is then used by the classes that represent the established, listening, and closed states. We can also have another class called Connection that can be used to represent the current state of TCP connection. The requests specific to the state object is delegated by the connection class and that uses an instance of the state to perform the intended operations to the state of a connection. Typically, whenever the state of the connection is changed the Connection object changes the state instance used by it. For example, say we have 3 instances of state objects to represent established, listening and closed states and Connection object is using the established instance for now and if anything changes, the connection object may replace the established instance with closed instance of the TCPState.

This state design pattern in Java example clearly explains the intent such that the object can alter its behavior when an internal state changes. The object appears to change its class. The state design pattern in Java is used to encapsulate the varying behavior of an object based on its internal state.

State Design Pattern Example in Java

Before we move on to demonstrate the code example of state design pattern in Java, let us first see what are the key classes (participants) we need to understand the example better.

  • Context Interface

The context defines an interface that maintains an instance of ConcreteState subclass that defines the current state.

  • State Interface

The state defines an interface for encapsulating the behavior associated with a particular state of the Context.

  • ConcreteState Subclasses

The Concrete state subclasses can be thought of as the instances of the connection object in- (established, listening or closed ) states as mentioned earlier. They implement the behavior of the state of the Context.

State Design Pattern in Java Example

We will demonstrate a highly simplified version of a start and pause feature of a game. The implementation is as follows:

 1. The State Interface

The state interface will be implemented by the different state classes to override the doAction method as per their requirement. This is just a blueprint for the different states.

State Interface

2. StartState Class

StartState is a concrete subclass that represents the “start state” of a game. It overrides the method inherited from the interface and also has a method that returns a string stating “start state”

Concrete Subclass (StartState)

3. Stop State Class

Stop state is also a concrete subclass of the state interface. The only variation is that it represents the “paused” state of the game.

Concrete Subclass (StopState)

4. Context

Context, as defined previously maintains the instance of a ConcreteState subclass, StopState or Start state in our case.

Context

5. State Design Pattern Demo

The startState.doAction method is passed the context object to set the current state of the application. The getState method of the context then returns the current state and the toString method inside of the concrete state class is used to perform the desired action defined by the current state.

State Design Pattern Demo

What Exactly Is Happening Here?

Context class delegates request that are specific to state to the ConcreteState object (startstate/stopstate in our case). The state object is being passed the context as an argument for accessing the context.

What Did We Achieve with The Help of The State Design Pattern in Java?

  • The state design pattern Java examples have shown us that it allowed us to add as many behaviors to an object based on its internal state.
  • The state design pattern in Java localizes behavior specific to the state. The code that is specific to a state lives in a state subclass and that makes it easier for us to add new states by defining new subclasses. This means that our code can easily be extended.
  • Even though the state design pattern in Java can increase the number of classes for representing different states. If that were not the case, then we would have ended up with large conditional statements for checking a lot of things. While using the state design pattern in Java we only need to determine whether the internal state of the object has changed or not.

In Conclusion

The state design pattern in Java should be used if we have different behavior for each state of our object. Possibilities are we may need to configure the transition at run time. It can come in handy in creating GUIs for a game as well. At run time the user may want a different interface for a particular level or the game itself might change the states according to the level of the game played.

Software design Java (programming language) Object (computer science) Connection (dance) Interface (computing)

Opinions expressed by DZone contributors are their own.

Related

  • User-Friendly API Publishing and Testing With Retrofit
  • Composite Design Pattern in Java
  • Iterator Design Pattern In Java
  • The Complete Guide to Stream API and Collectors in Java 8

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!