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
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

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • State Design Pattern In Java
  • Maven Archetypes: Simplifying Project Template Creation
  • How To Remove Excel Worksheets Using APIs in Java
  • Javac and Java Katas, Part 2: Module Path

Trending

  • The Rise of Kubernetes: Reshaping the Future of Application Development
  • Setting up Device Cloud: A Beginner’s Guide
  • AWS CDK: Infrastructure as Abstract Data Types
  • Implementing Real-Time Credit Card Fraud Detection With Apache Flink on AWS
  1. DZone
  2. Coding
  3. Java
  4. State Pattern Tutorial with Java Examples

State Pattern Tutorial with Java Examples

Learn the State Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Jun. 09, 10 · Tutorial
Like (17)
Save
Tweet
Share
137.3K Views

Join the DZone community and get the full member experience.

Join For Free

Today's pattern is the State pattern, which allows objects to behave in different ways depending on internal state. State is used when you need a class to behave differently, such as performing slightly different computations, based on some arguments passed through to the class.

State in the Real World 

Vending machines maintain an internal state which allow it to change it's behaviour accordingly. For example, if there is no change available, it will demand exact change. When something is out of stock, it will deliver none of that product. 

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The State Pattern

The State pattern is known as a behavioural pattern - it's used to manage algorithms, relationships and responsibilities between objects. Thedefinition of State provided in the original Gang of Four book on DesignPatterns states: 

Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.

 

Let's take a look at the diagram definition before we go into more detail.




The Context can have a number of internal States, whenever the request() method is called on the Context, the message is delegated to the State to handle. The State interface defines a common interface for all concrete states, encapsulating all behaviour associated with a particular state. The ConcreteState implements it's own implementation for the request. When a Context changes state, what really happens is that we have a different ConcreteState associated with it.

This is all quite similar to the Strategy pattern, except the changes happen at runtime rather than the client deciding. State saves you from lots of conditional code in your Context: by changing the ConcreteState object used, you can change the behaviour of the context.

Would I Use This Pattern?

You should use the State pattern when the behaviour of an object should be influenced by it's state, and when complex conditions tie object behaviour to it's state.

So How Does It Work In Java?

We'll use the state of an mp3 player to give an example of the state pattern in action. First we set up a context for our mp3 playe.

//Context
public class MP3PlayerContext {
  private State state;
  private MP3PlayerContext(State state) {
    this.state= state;
  }
  public void play() {
    state.pressPlay(this);
  }
  public void setState(State state) {
    this.state = state;
  }
  public State getState() {
    return state;
  }
}

Now we'll create our state interface. In this example, we've just got a play button.

private interface State {
  public void pressPlay(MP3PlayerContext context);
}

And finally, creating a state for Standby and for Playing. 

public class StandbyState implements State {
  public void pressPlay(MP3PlayerContext context) {
    context.setState(new PlayingState());
  }
}

public class PlayingState implements State {
  public void pressPlay(MP3PlayerContext context) {
    context.setState(new StandbyState());
  }
}

So this shows how the state pattern works at a simple level. Of course, our pressPlay methods would do more than simply set the state of the context. 

Watch Out for the Downsides

There are some potential bad uses of the state pattern. For example, some operations may not be possible when the context is in certain states. This article proposes a nice solution to the problem.

Next Up

Just one pattern left now - The Builder Pattern. We'll be covering that in the next few days.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern


State pattern Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • State Design Pattern In Java
  • Maven Archetypes: Simplifying Project Template Creation
  • How To Remove Excel Worksheets Using APIs in Java
  • Javac and Java Katas, Part 2: Module Path

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: