Open main menu

CDOT Wiki β

Changes

State

1,618 bytes added, 09:51, 23 March 2007
Code Samples
== Code Samples ==
 
=== Greeting Message Generator ===
 
[http://matrix.senecac.on.ca/~rmwang/btppresentation/sunsample.html Click here to see the UML diagram for this example]
 
'''State class interface definition'''
<pre>
class CBaseState
{
public:
virtual CBaseState* GetNextState() = 0;
virtual char* ToString() = 0;
};
</pre>
 
'''Concrete class definitions'''
<pre>
 
class CMorning : public CBaseState{
public:
virtual CBaseState* GetNextState();
virtual char* ToString();
};
 
class CEvening : public CBaseState{
public:
virtual CBaseState* GetNextState();
virtual char* ToString();
};
 
class CNight: public CBaseState{
public:
virtual CBaseState* GetNextState();
virtual char* ToString();
};
 
</pre>
'''Context class structure'''
<pre>
class CSun{
public:
CSun();
CSun(CBaseState* pContext);
~CSun();
void StateChanged();
char* GetStateName();
protected:
void DoCleanUp();
CBaseState* m_pState;
};
</pre>
'''Function definition for state change'''
<pre>
void CSun::StateChanged(){
if (m_pState){
CBaseState* pState = m_pState->GetNextState();
delete m_pState;
m_pState = pState;
}
}
</pre>
 
 
 
 
'''Code that changes state'''
<pre>
CBaseState* CMorning::GetNextState(){return new CEvening;}
CBaseState* CEvening::GetNextState(){return new CNight;}
CBaseState* CNight::GetNextState(){return new CMorning;}
</pre>
'''Simple example of actual implementation'''
<pre>
CSun objSun(new CMorning);
printf("\n\nSun Says Good %s !!!",objSun.GetStateName());
objSun.StateChanged();
printf("\n\nSun Says Good %s !!!",objSun.GetStateName());
objSun.StateChanged();
printf("\n\nSun Says Good %s !!!",objSun.GetStateName());
objSun.StateChanged();
printf("\n\nSun Says Good %s !!!",objSun.GetStateName());
</pre>
 
=== Game programming: Character Status ===
[http://matrix.senecac.on.ca/~rmwang/btppresentation/statesample.html Click here to see the UML diagram for this example]
}
</pre>
=== Greeting Message Generator ===
 
[http://matrix.senecac.on.ca/~rmwang/btppresentation/sunsample.html Click here to see the UML diagram for this example]
== References ==
1
edit