State Design Pattern

I

Immortal Nephi

Every time, the code begins to invoke class’ constructor function and
process algorithms before invoke class’ 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 class’ 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.

class Machine
{
private:
class State *current;

public:

Machine();
void setCurrent(State *s)
{
current = s;
}

void on();
void off();
};

class State
{
public:
virtual void on(Machine *m)
{
cout << " already ON\n";
}

virtual void off(Machine *m)
{
cout << " already OFF\n";
}
};

void Machine::eek:n()
{
current->on(this);
}

void Machine::eek:ff()
{
current->off(this);
}

class ON: public State
{
public:
ON()
{
cout << " ON-ctor ";
};

~ON()
{
cout << " dtor-ON\n";
};

void off(Machine *m);
};

class OFF: public State
{
public:
OFF()
{
cout << " OFF-ctor ";
};

~OFF()
{
cout << " dtor-OFF\n";
};

void on(Machine *m)
{
cout << " going from OFF to ON";
m->setCurrent(new ON());
delete this;
}
};

void ON::eek:ff(Machine *m)
{
cout << " going from ON to OFF";
m->setCurrent(new OFF());
delete this;
}

Machine::Machine()
{
current = new OFF();
cout << '\n';
}

int main()
{
void(Machine:: *ptrs[])() =
{
Machine::eek:ff, Machine::eek:n
};

Machine fsm;
int num;

while (1)
{
cout << "Enter 0/1: ";
cin >> num;
(fsm. *ptrs[num])();
}

return 0;
}
 
J

Jonathan Lee

Why do you need to invoke on class and off class’ constructor
function during run-time?

Indeed, why would you? Really.. if your FSM has only two states I
think you're better off storing a bool and flipping it with on() and
off() methods.

Your question is like asking why you would a sledgehammer to pound
in a nail. You wouldn't. Use a regular hammer.

On the other hand, if you _need_ construction and destruction,
many different abstract states, and/or extensibility, then use the
State Design Pattern.

The Wikipedia article has such an example.

--Jonathan
 
I

Immortal Nephi

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 at http://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. Put state behavior and some member functions in
one base class. You will need to split class if class is getting
bigger. Several class definitions are written and they call state
class’ variables through indirection pointer outside their class
definitions.
 
I

Immortal Nephi

Certainly not in this simple case. Something like this:

class Machine
{
   void (Machine::*doOn)();
   void (Machine::*doOff)();
   void alreadyOn() {
      cout << " already On\n";
   }
   void alreadyOff() {
      cout << " already Off\n";
   }
   void offToOn() {
      cout << " going from Off to On\n";
      doOn = &Machine::alreadyOn;
      doOff = &Machine::eek:nToOff;
   }
   void onToOff() {
      cout << " going from On to Off\n";
      doOn = &Machine::eek:ffToOn;
      doOff = &Machine::alreadyOff;
   }
public:
   Machine(): doOn(&Machine::eek:ffToOn), doOff(&Machine::alreadyOff) { }
   void on() {
      (this->*doOn)();
   }
   void off() {
      (this->*doOff)();
   }

};

Works fine without the added overhead of constantly newing stateless
objects.

However, I am probably jumping the gun a bit. It is the nature of
samples and examples like this to use more structure than is needed for
a given problem in order to illustrate how to structure more complex
problems.

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.- Hide quoted text -

- Show quoted text -

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.
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.

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;
}
 
J

James Kanze

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.

Why? Each of the types has a distinctive behavior; in the
classical state machine implementation, the behavior is the only
information needed in the representation of the state.

In this case, it's perfectly possible (and indeed the usual
solution) to declare a static instance of each type, and use it,
rather than constructing a new instance on each state
transition.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,696
Latest member
BarbraOLog

Latest Threads

Top