Re: State Design Pattern
Immortal Nephi <Immortal_Nephi@hotmail.com> wrote:
On May 2, 6:08?pm, "Daniel T." <danie...@earthlink.net> wrote:
Immortal Nephi <Immortal_Ne...@hotmail.com> wrote:
On May 2, 2:04?pm, "Daniel T." <danie...@earthlink.net> wrote:
Immortal Nephi <Immortal_Ne...@hotmail.com> wrote:
? ?Every time, the code begins to invoke class1 constructor function
and
process algorithms before invoke class1 destructor function. ?It uses
new operator and delete operator. ?Doing that way is very slow.
? ?The state design pattern is an example. ?The state class has on /
off
switch. ?Why do you need to invoke on class and off class1
constructor
function during run-time?
? ?Why not loading on class and off class into memory before program
starts? ?After the program terminates, it takes care to clean up
memory.
Something to note here is that in your sample code, none of the
'State',
'On' or 'Off' classes encapsulate data. This observation serves as a
red
flag ("bad smell" if you will,) that you might be using the wrong level
of abstraction.
Just something to consider.
? ?Please take a look
athttp://sourcemaking.com/design_patterns/state/cpp/1.
I copied and pasted sample code here.
? ?I think you are suggesting. ?You do not need to write two derived
classes ON and OFF.
[snip]
Even so, I am uncomfortable with the fact that it made
setCurrent(State*) public and newing On and Off objects. Better would be
to make the setter private and make State a friend of Machine, and
statically construct a single onState and offState object. However, now
I'm just talking about variations on a theme.
On second glance, maybe you should just ignore everything I posted in
this thread. Sorry.
Please do not say anyone to ignore your post. Your example looks
very good. State class is like an internal structure. It has some
data fields. The data fields describes on / off, keypads, and some
logical choices.
Let me clarify more details. Your code will be confused if class
definition is too big with many member functions and data fields. Few
member functions are available to the client.
My question is: do you want the client to see your several class
definitions? Maybe, all of your class definitions do not have
encapsulation or you put them in private implementation. Or?do you
want the client to include and reuse your several class definitions
through inheritance? Maybe, you don?t want the client to see yours.
When using the state pattern, you don't want the client creating new
state sub-classes or state objects by definition. The fact that you use
the pattern should not be apparent to users of the Machine class (true
containment.) The state class, and all its sub-classes should be hidden
from users of Machine, or at the very least in a separate translation
unit that users of Machine don't need to include.
Data and methods that are only associated with a single state should be
in the state sub-class, but there are options on where to put
data/methods that are associated with all states. They could be put in
the State base class or in the Machine class itself, where to put them
should be decided by what happens to them when state changes. If the
State objects have no data, then they shouldn't be newed/deleted,
instead make static instances of each one.
For the "ON/OFF machine" that you originally presented, I think
something like this is most appropriate:
class State {
public:
virtual void doOn() = 0;
virtual void doOff() = 0;
};
class OnState : public State {
void doOn() { cout << " already On\n"; }
void doOff() { cout << " going from On to Off\n"; }
} onState;
class OffState : public State {
void doOn() { cout << " going from Off to On\n"; }
void doOff() { cout << " already Off\n"; }
} offState;
class Machine
{
State* currentState;
public:
Machine(): currentState(&offState) { }
void on() {
currentState->doOn();
currentState = &onState;
}
void off() {
currentState->doOff();
currentState = &offState;
}
};
int main()
{
void(Machine:: *ptrs[])() =
{
&Machine::off, &Machine::on
};
Machine fsm;
int num;
while (1)
{
cout << "Enter 0/1: ";
cin >> num;
(fsm.*ptrs[num])();
}
}
If you put the functions in the cpp file like normal, then the State,
OnState and OffState classes can all go in Machine.cpp.
The class A, class B, class C, and class state are in private
implantation. They are like internal structure to contain many
private algorithms. Only class interface is available to the client.
The client includes class interface in his code. He invokes class
interface?s run() function. The run() function does all the jobs for
him. It calls class A, class B, or class C before it is in turn to
call class state when they need to access class state?s data fields
through interface?s member functions.
You say, ?Works fine without the added overhead of constantly newing
stateless objects.? I agree with you. Setters and getters will be
added more overhead because member function accesses data field from
class to another class through pointer. All setters and getters
functions are eliminated if you turn on C++ Compiler?s optimization.
Take a look at my code. You will see what I mean. All classes have
a relationship to class state when they communicate each other to
modify class state?s data fields.
Several class definitions are much clear to reduce complex and
confusion.
I consider what you have below to be a very bad design decision. Using
this anti-pattern allows objects to change each others state, *without*
going through the object's interface. Your code vaguly reminds me of a
poorly implemented Observer pattern, rather than a State.
When State objects contain data, Machine objects should not share them.
Better would be to either have each Machine instance carry a single copy
of each state to swap through, or new/delete State objects as necessary.
Which rout you take depends on how heavy the state objects are and how
often Machines are likely to change states.
class state
{
private:
char m_register;
char m_register2;
char m_register3;
bool m_power;
public:
state() : m_register( 0 ), m_register2( 0 ), m_register3( 0 ),
m_power( false ) {}
~state() {}
void set_register( char value ) { m_register = value; }
void set_register2( char value ) { m_register2 = value; }
void set_register3( char value ) { m_register3 = value; }
char get_register() const { return m_register; }
char get_register2() const { return m_register2; }
char get_register3() const { return m_register3; }
void turn_off() { m_power = false; }
void turn_on() { m_power = true; }
bool isTurn_on() const { return m_power; }
};
class A
{
private:
state *m_state;
public:
A() {}
~A() {}
void init( state &rState )
{
m_state = &rState;
}
void Put_Data( char value ) { m_state->set_register( value ); }
char Get_Data() const { return m_state->get_register(); }
};
class B
{
private:
state *m_state;
public:
B() {}
~B() {}
void init( state &rState )
{
m_state = &rState;
}
void Put_Data( char value ) { m_state->set_register2( value ); }
char Get_Data() const { return m_state->get_register2(); }
};
class C
{
private:
state *m_state;
public:
C() {}
~C() {}
void init( state &rState )
{
m_state = &rState;
}
void Put_Data( char value ) { m_state->set_register3( value ); }
char Get_Data() const { return m_state->get_register3(); }
};
class Interface
{
private:
state m_state;
A m_A;
B m_B;
C m_C;
void Put_Key_1( char value ) { m_A.Put_Data( value ); }
void Put_Key_2( char value ) { m_B.Put_Data( value ); }
void Put_Key_3( char value ) { m_C.Put_Data( value ); }
char Get_Key_1() const { return m_A.Get_Data(); }
char Get_Key_2() const { return m_B.Get_Data(); }
char Get_Key_3() const { return m_C.Get_Data(); }
void TurnOn_Power() { m_state.turn_on(); }
void TurnOff_Power() { m_state.turn_off(); }
bool isPower() { return m_state.isTurn_on(); }
public:
Interface()
{
m_A.init( m_state );
m_B.init( m_state );
m_C.init( m_state );
}
~Interface() {}
void Run()
{
bool exit = true;
while( exit )
{
char input;
char keys;
while( isPower() )
{
cout << "Press [1-3] to store data into memory or [0] to turn off
power." << endl;
cout << "Prompt: ";
cin >> input;
cout << ends << endl;
switch( input )
{
case '0':
TurnOff_Power();
cout << "Power is off." << endl;
break;
case '1':
cout << "1) Enter one character: ";
cin >> keys;
Put_Key_1( keys );
cout << "\nMemory location: " << Get_Key_1() << ends << endl;
break;
case '2':
cout << "2) Enter one character: ";
cin >> keys;
Put_Key_2( keys );
cout << "\nMemory location: " << Get_Key_2() << ends << endl;
break;
case '3':
cout << "3) Enter one character: ";
cin >> keys;
Put_Key_3( keys );
cout << "\nMemory location: " << Get_Key_3() << ends << endl;
break;
default:
cout << "Invalid input. Try again." << endl;
} // end switch
} // end while
cout << "Enter [1-2] to switch power or [0] to exit." << endl;
cout << "Prompt: ";
cin >> input;
cout << ends << endl;
switch( input )
{
case '0':
cout << "Good-bye." << endl;
exit = false;
break;
case '1':
TurnOn_Power();
cout << "Power is on." << endl;
break;
case '2':
TurnOff_Power();
cout << "Power is off." << endl;
break;
default:
cout << "Invalid input. Try again." << endl;
} // end switch
}
}
};
int main()
{
Interface cInterface;
cInterface.Run();
return 0;
}