You are on page 1of 2

State Pattern:The state pattern is used to represent the state of the object in the computer programming.

this is a simple way for object to change the types in the runtime. when any object change the state then it information is represented by the its member class.

Benefit and use: The state pattern is control many states without using any conditional statement. this is use a class for representation of object state. In this the every state is perform the act in similar manner. Every state contain to the subclass of the super class. It is Simplify the program and clarify it.

Example:package r4r; interface State { void writeName(StateView sv, String name); } class A implements State { public void writeName(StateView sv, String name) { System.out.println(name.toUpperCase()); sv.setState(new B()); } } class B implements State { private int count=0; public void writeName(StateView sv, String name){ System.out.println(name.toLowerCase()); // change state after B writeName() gets invoked twice if(++count>1) { sv.setState(new A()); } } } class StateView { private State myStatestatus; public StateView() { setState(new A()); } public void setState(State newState) { this.myStatestatus = newState; } public void writeName(String name) { this.myStatestatus.writeName(this, name);

} } public class statetest { public static void main(String[] args) { StateView sv = new StateView(); sv.writeName("January"); sv.writeName("February"); sv.writeName("March"); sv.writeName("April"); sv.writeName("May"); sv.writeName("June"); sv.writeName("July"); sv.writeName("August"); sv.writeName("September"); sv.writeName("October"); sv.writeName("November"); sv.writeName("December"); } }

You might also like