State Design Pattern:
State pattern is to alter an object behavior when its state changes.
It is behavioral software design pattern.
Classic real time example of state pattern is ToggleButton which when press first becomes on and when press again becomes off.
So if you want to implement that toggle button you can use the state pattern so that its state change at runtime.
Following is the class diagram for the same.

(Click to Enlarge)
Code :
State
package com.milind.design.pattern.gof.behavioral;
/**
* This is the abstract state
* @author milind
*/
public interface ButtonState {
public void pressButton(ToggleButton btn);
}
Context
package com.milind.design.pattern.gof.behavioral;
/**
* This is the context which will be called by the client.
* @author milind
*
*/
public class ToggleButton {
private ButtonState state;
public ToggleButton() {
// Making the on state in begining
this.state = new OnState();
}
public ButtonState getState() {
return state;
}
public void setState(ButtonState state) {
this.state = state;
}
public void pressButton() {
this.state.pressButton(this);
}
}
Concrete On State:
package com.milind.design.pattern.gof.behavioral;
/**
* Concrete State
* @author milind
*/
public class OnState implements ButtonState{
public void pressButton(ToggleButton btn) {
System.out.println("Light Is Switched On ...");
btn.setState(new OffState());
}
}
Concrete Off State
package com.milind.design.pattern.gof.behavioral;
/**
* Concrete State
* @author milindaol
*/
public class OffState implements ButtonState{
public void pressButton(ToggleButton btn) {
System.out.println("Light Is Switched Off ...");
btn.setState(new OnState());
}
}
Client
package com.milind.design.pattern.gof.behavioral;
/**
*
* @author milindaol
*/
public class Client {
public static void main(String[] args) {
//Creating the Context
ToggleButton btn = new ToggleButton();
//Swithchin on the light.
btn.pressButton();
//Swithchin off the light.
btn.pressButton();
//Testing for three times
for(int i=0;i<3;>
btn.pressButton();
}
}
}
No comments:
Post a Comment