State Design Pattern

Discussion in 'C++' started by Immortal Nephi, May 2, 2010.

  1. 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;
    }
    Immortal Nephi, May 2, 2010
    #1
    1. Advertising

  2. Immortal Nephi

    Jonathan Lee Guest

    On May 2, 11:21 am, Immortal Nephi <> wrote:
    > 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
    Jonathan Lee, May 2, 2010
    #2
    1. Advertising

  3. On May 2, 2:04 pm, "Daniel T." <> wrote:
    > Immortal Nephi <> wrote:
    > >    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.

    >
    > 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.
    Immortal Nephi, May 2, 2010
    #3
  4. On May 2, 6:08 pm, "Daniel T." <> wrote:
    > Immortal Nephi <> wrote:
    > > On May 2, 2:04 pm, "Daniel T." <> wrote:
    > > > Immortal Nephi <> 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.

    >
    > 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;
    }
    Immortal Nephi, May 3, 2010
    #4
  5. Immortal Nephi

    James Kanze Guest

    On 2 May, 20:04, "Daniel T." <> wrote:
    > Immortal Nephi <> wrote:
    > > 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.


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

    --
    James Kanze
    James Kanze, May 4, 2010
    #5
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    8
    Views:
    695
    bruno modulix
    Aug 11, 2005
  2. sunny
    Replies:
    1
    Views:
    451
    Salt_Peter
    Dec 7, 2006
  3. Pallav singh
    Replies:
    0
    Views:
    345
    Pallav singh
    Jan 22, 2012
  4. Pallav singh
    Replies:
    0
    Views:
    390
    Pallav singh
    Jan 22, 2012
  5. Pallav singh
    Replies:
    1
    Views:
    443
    Peter Remmers
    Jan 22, 2012
Loading...

Share This Page