Alexey Zvolinskiy

About Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Design Patterns: State

This article will be about State design pattern. It is one of behavioral design patterns. You don’t need to know many theory to understand the main concepts of the pattern. The post will be break in several parts where I will provide information about situations where the pattern need to be applied, cons and pros which it has and an example of usage.java-design-patterns

Sometimes you need to change a behavior of object when its internal state changes. The State design pattern allows to do this. You can obtain this by creation of separate classes which represent different states and functionality. Of Course these classes have to be inherited from one abstract class or implement one interface.

The State design pattern can be used when we need to change state of object at runtime by inputting in it different subclasses of some State base class. This circumstance is advantage and disadvantage in the same time, because we have a clear separate State classes with some logic and from the other hand the number of classes grows up.

Let’s consider the example. Each year has 4 seasons: Winter, Spring, Summer and Autumn.Each season has its own order, e.g. Spring comes after Winter, Summer comes after Spring and so on.

Base state interface for the seasons:

public interface Season {
	public void theSeason(SeasonContext context);
}

Strategy-Design-Pattern

State classes which implement the Season interface:

public class Winter implements Season {

	@Override
	public void theSeason(SeasonContext context) {
		System.out.println("Winter is now.");
		context.setSeason(new Spring());
	}

}

Spring class:

public class Spring implements Season {

	@Override
	public void theSeason(SeasonContext context) {
		System.out.println("Spring is now");
		context.setSeason(new Summer());
	}

}

I’ll omit classes for Summer and Autumn, because they are the same as previous classes.

The SeasonContext class:

public class SeasonContext {
	private Season season;

	public SeasonContext() {
		this.season = new Winter();
	}

	public void setSeason(Season season) {
		this.season = season;
	}

	public void whatTheSaeson() {
		season.theSeason(this);
	}
}

All this stuff shows architecture of the State pattern: base state interface, classes which implement the state interface and the state context. Now let’s see how it works:

...
	public static void main(String[] args) {
		SeasonContext sc = new SeasonContext();
		sc.whatTheSaeson();
		sc.whatTheSaeson();
		sc.whatTheSaeson();
		sc.whatTheSaeson();
	}
...

The result will be:

Winter is now.
Spting is now
Summer is now.
Autumn is now.

 

Reference: Design Patterns: State from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

2 Responses to "Design Patterns: State"

  1. Really informative post .
    Composite design pattern is based on creating a tree structure in such a way that an individual leaf of the tree can be treated just like entire tree composition.

  2. manoj says:

    State design pattern works on the concept of state change. Entire process life-cycle can be divided in multiple phases.With completion of each phase process exits from one state and enters in to another state.

    For example In JSF framework entire web request response lifecycle is divided in six phases:

    After completion of every phase process exits from a state and enters into another state. For example after RestoreValuePhase we can say ViewRestored as exit state and RequestApply as entering state .

    So to implement State design pattern It is required to divide entire process in such a way that It can be processed in multiple phases with every phase exit defining a state change.

    Now let’s understand this with below code.

    Any project lifecycle can be divided in multiple phases like

    requirementAssessment
    Design
    Development
    QualityAssessment
    Deploy
    Closure

    So these are the phases used in below example

    Rules :

    1. We need to define a class where we can store the current state of the process. NextPhase class in below code is doing that.

    2. We need to define an Interface wherein we can provide the contact method that would be implemented in each phase.In below code ProjectPhase is doing that.

    Learn more about State design pattern here — State Design Pattern

    http://efectivejava.blogspot.in/2013/09/java-state-design-patten-oops-state.html?utm_source=BP_recent

Leave a Reply


− 2 = five



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close