Java state design pattern

Java state design pattern comes under behavioural design patterns. State design pattern is used when an Object change its behavior based on its state. State design pattern implementation consists of objects which represent different states and a context object whose behavior changes based on object state changes.

Let’s discuss state design pattern with below example. We are taking here an example of AC remote. It have one button to on and off the AC. AC will turn on when state is on and AC will be turn off if the state is off.

Example

State.java

package com.w3spoint;
 
public interface State {
	public void doAction(); 
}

ACStartState.java

package com.w3spoint;
 
public class ACStartState implements State {
	@Override
	public void doAction() {
		System.out.println("AC is on.");
	}		
}

ACStopState.java

package com.w3spoint;
 
public class ACStopState implements State {
	@Override
	public void doAction() {
		System.out.println("AC is off.");
	}		
}

ACContext.java

package com.w3spoint;
 
public class ACContext implements State {
	private State acState;
 
	public void setState(State state) {
		this.acState=state;
	}
 
	public State getState() {
		return this.acState;
	}
 
	@Override
	public void doAction() {
		this.acState.doAction();
	}
}

CommandPatternTest.java

package com.w3spoint;
 
public class CommandPatternTest {
	public static void main(String args[]){
		ACContext acContext = new ACContext();
		State acStartState = new ACStartState();
		State acStopState = new ACStopState();
 
		acContext.setState(acStartState);
		acContext.doAction();
 
 
		acContext.setState(acStopState);
		acContext.doAction();
	}
}

Output

AC is on.
AC is off.
Content Protection by DMCA.com
Please Share