----------------------------
class State
{
public:
State(){};
~State(){};
virtual void on(Machine *m) {};
virtual void off(Machine *m) {} ;
};
class Machine
{
class State *current;
public:
Machine();
~Machine(){delete current;}
void setCurrentState(State *s)
{
current = s;
}
void on();
void off();
};
class ONN:public State
{
public:
ONN(){cout<<"ON Ctr"<
void off(Machine *m);
};
class OFFF:public State
{
public:
OFFF(){cout<<"OFF Ctr"<
void on(Machine *m)
{
cout <<"OFF to ON"<
m->setCurrentState(new ONN());
delete this;
}
};
Machine::Machine(){current = new OFFF();}
void ONN::off(Machine *m)
{
cout<<"ON to OFF"<
delete this;
}
void Machine::on(){ current->on(this);}
void Machine::off() {current->off(this);}
int main(int argc, char * argv[])
{
typedef void (Machine::*ptr)();
ptr ptr_arr[2];
Machine fsm;
ptr_arr[0] = &Machine::off;
ptr_arr[1] = &Machine::on;
int num;
while(1)
{
cout<<"enter 0-->Off and 1-->On"<
(fsm.*ptr_arr[num])();
}
}
Output:
enter 0-->Off and 1-->On
1
OFF to ON
ON Ctr
enter 0-->Off and 1-->On
1
ON
enter 0-->Off and 1-->On
0
ON to OFF
No comments:
Post a Comment