mercredi 1 juin 2016

"State pattern" vs "one member function per state"?

My class has 3 states. In each state it does some work, and goes to other state, or remains in the same state (in 95% or more cases it will stay in the same state). I can implement state pattern (I assume you know it). The alternative, which I pretty like, is this:

I have a member function per state, and also a pointer to member function, which points to the current state function. When in a state I want to go to another state, I just point that function pointer to another state function. (maybe this isn't completely equivalent to state pattern, but in my case it works fine).

Those two ways are almost identical, I think.

So, my questions are:

  1. Which solution is better (depends on what)?
  2. Is it worth to declare a class per state (which will have only one function)? I think that would be artificial.
  3. What about performance? isn't creating new object of state class (in case of state pattern) bring with it a slight overhead? (Sure state classes shouldn't have members, but anyway it should cost something)

Aucun commentaire:

Enregistrer un commentaire