Definition -
This is a pattern where in the object changes its behavior based on the state.
Scenario -
Let us consider a scenario where in the windshield of your car has to start the wiper if the rain starts or it needs to enable polarized light depending on the intensity of light.
Based on the above -
1) A interface called eventstate which will have a method called performaction.
2) A class rain which will implement the eventstate.
3) A class day which will implement the eventstate.
4) A windshieldcontext which will perform action based on state.
5) The client code for the same is given below
Place to use -
1) When you have want the object to behave different in different scenarios and at the sametime decouple the systems so that the conditions are decided only in run time and not in compile time.
The code for the above is present in the link here
This is a pattern where in the object changes its behavior based on the state.
Scenario -
Let us consider a scenario where in the windshield of your car has to start the wiper if the rain starts or it needs to enable polarized light depending on the intensity of light.
Based on the above -
1) A interface called eventstate which will have a method called performaction.
package StatePattern;
public interface eventstate {
public void performaction();
}
2) A class rain which will implement the eventstate.
package StatePattern;
public class rain implements eventstate {
@Override
public void performaction() {
System.out.println("Wiper will be turned on");
}
}
3) A class day which will implement the eventstate.
package StatePattern;
public class day implements eventstate {
@Override
public void performaction() {
System.out.println("Wiper will be turned on");
}
}
4) A windshieldcontext which will perform action based on state.
package StatePattern;
public class windshieldcontext implements eventstate {
eventstate es;
public void setcontext(eventstate e) {
this.es=e;
}
@Override
public void performaction() {
this.es.performaction();
}
}
5) The client code for the same is given below
package StatePattern;
public class statedemo {
public static void main(String args[]) {
eventstate es;
windshieldcontext ws=new windshieldcontext();
String states="Rain";
if(states.equalsIgnoreCase("Rain")) {
es=new rain();
ws.setcontext(es);
}
else if(states.equalsIgnoreCase("Day")) {
es=new day();
ws.setcontext(es);
}
ws.performaction();
}
}
Place to use -
1) When you have want the object to behave different in different scenarios and at the sametime decouple the systems so that the conditions are decided only in run time and not in compile time.
The code for the above is present in the link here
No comments:
Post a Comment