Re: SetMode(Enum) vs. SetModeA(), SetModeB()...
{ Edits: quoted signature and clc++m banner removed. -mod }
On May 4, 10:11 am, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
wrote:
chase.bradf...@saic.com ha scritto:
When writing a class that can be in exactly one of many modes, what
interface should I provide for changing the mode?
As proposed by another poster, I would consider the State pattern.
Two techniques come to mind for this.
1) Define a Mode enumerated type, with a method SetMode that takes a
Mode argument and switches across them.
2) For each mode, have a no argument method to change into that mode.
I can think of some cases where technique 1 is preferred, for
instance, when the mode needs to be stored as a variable and restored
later. This could occur in the case of a stack, where changing modes
pushes current modes onto a stack, then unwinding could be performed
with SetMode( stack.top() ).
You easily achieve the same even in approach 2, by using a stack of
pointer-to-member-functions. That is:
std::stack<void (MyClass::*)()> modes;
modes.push(&MyClass::SetModeA);
(obj.*modes.top())(); // set obj in mode "A"
(this->*modes.top())(); // set *this in mode "A"
I agree for the most part with the State pattern.
struct Marker
{
virtual ~Marker() = 0;
};
struct ModeA : Marker
{
virual ~ModeA() {}
};
struct ModeB: Marker
{
virtual ~ModeB() {}
};
.. . .
void setMode(Mode mode) {} // guaruntees a mode - can use overloading
to prevent dynamic casting - plain Mode won't compile since it is
abstract.
.. . .
setMode((ModeA));
As always, I never test my code before I post, so you may or may not
need the extra set of parens. Also, try a const& if that doesn't work
either.
I'm off to the store to buy candy for the movies!
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]