I read this link enter link description here, to learn State Desing Patern.
interface class:
public interface State {
void doAction();
}
onState class:
public class TVStartState implements State {
@Override
public void doAction() {
System.out.println("TV is turned ON");
}
}
offState:
public class TVStopState implements State {
@Override
public void doAction() {
System.out.println("TV is turned OFF");
}
}
TvContext Class:
public class TVContext implements State {
private State tvState;
public void setState(State state) {
this.tvState=state;
}
public State getState() {
return this.tvState;
}
@Override
public void doAction() {
this.tvState.doAction();
}
}
test Class :
public static void main(String[] args) {
TVContext context = new TVContext();
State tvStartState = new TVStartState();
State tvStopState = new TVStopState();
context.setState(tvStartState);
context.doAction();
context.setState(tvStopState);
context.doAction();
}
Now I have two questions :
1- why TVContext Class implements
State and has Composition
toghether ? is a bug in OO ? because for example Cat inherits from Animal class and has_a animal together (in this case).
2-If The final programmer in this TestClass pass context to context.setState()
instead tvStartState or tvStopState , Program successfully compiles but error in run_time.
For the second question in State Design Pattern, instead of inheritance, same name method
can be used. but int Decoration Design Pattern not.
Aucun commentaire:
Enregistrer un commentaire