State Design Pattern in Java – Example Tutorial

About Pankaj Kumar

State pattern is one of the behavioral design pattern. State design pattern is used when an Object change it’s behavior based on it’s internal state.

If we have to change the behavior of an object based on it’s state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations.

Context is the class that has a State reference to one of the concrete implementations of the State and forwards the request to the state object for processing. Let’s understand this with a simple example.

Suppose we want to implement a TV Remote with a simple button to perform action, if the State is ON, it will turn on the TV and if state is OFF, it will turn off the TV.

We can implement it using if-else condition like below;

package com.journaldev.design.state;public class TVRemoteBasic {	private String state="";	public void setState(String state){		this.state=state;	}	public void doAction(){		if(state.equalsIgnoreCase("ON")){			System.out.println("TV is turned ON");		}else if(state.equalsIgnoreCase("OFF")){			System.out.println("TV is turned OFF");		}	}	public static void main(String args[]){		TVRemoteBasic remote = new TVRemoteBasic();		remote.setState("ON");		remote.doAction();		remote.setState("OFF");		remote.doAction();	}}

Source : http://www.javacodegeeks.com/2013/08/state-design-pattern-in-java-example-tutorial.html

Back to Top