Status Mode
GOOD: when an object's behavior depends on its state and it must change its behavior according to its state at runtime, the state mode can be considered.
[Html]
# Include <iostream>
Using namespace std;
Class Work;
Class ForenoonState;
Class NoonState;
Class State
{
Public:
Virtual void WriteProgram (Work * w) = 0;
};
Class Work
{
Private:
State * current;
Public:
Double hour;
Public:
Work ();
Void SetState (State * temp)
{
Current = temp;
}
Void Writeprogram ()
{
Current-> WriteProgram (this );
}
};
Class NoonState: public State
{
Public:
Virtual void WriteProgram (Work * w)
{
Cout <"execute" <endl;
If (w-> hour) <13)
Cout <"pretty good" <endl;
Else
Cout <"no, go to bed" <endl;
}
};
Class ForenoonState: public State
{
Public:
Virtual void WriteProgram (Work * w)
{
If (w-> hour) <12)
Cout <"the current spirit is invincible" <endl;
Else
{
W-> SetState (new NoonState ());
W-> Writeprogram (); // Add this sentence.
}
}
};
Work: Work ()
{
Current = new ForenoonState ();
}
// Client:
Int main ()
{
Work * mywork = new Work ();
Mywork-> hour = 9;
Mywork-> Writeprogram ();
Mywork-> hour = 14;
Mywork-> Writeprogram ();
Return 0;
}