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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Trending

  • Member Spotlight: Raghava Dittakavi
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices
  • A Field Guide to AI Agent Frameworks
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jun. 09, 10 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
139.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook