State Pattern Article Index for
State
Website Links For
State
 

Information About

State Pattern




The state pattern is a Behavioral Software Design Pattern , also known as the '''objects for states pattern'''. This pattern is used in Computer Programming to represent the state of an Object . This is a clean way for an object to partially change its type at runtime.

Take for example, a drawing program, in which there could be an Abstract Interface representing a tool, then Concrete Instance s of that class could each represent a kind of tool. When the user selects a different tool, the appropriate tool would be Instantiated .

For example, an interface to a drawing tool could be

class AbstractTool {
public:
virtual void MoveTo(const Point& inP) = 0;
virtual void MouseDown(const Point& inP) = 0;
virtual void MouseUp(const Point& inP) = 0;
};
Then a simple pen tool could be
class PenTool : public AbstractTool {
public:
PenTool() : mMouseIsDown(false) {}
virtual void MoveTo(const Point& inP) {
if(mMouseIsDown) {
DrawLine(mLastP, inP);
}
mLastP = inP;
}
virtual void MouseDown(const Point& inP) {
mMouseIsDown = true;
mLastP = inP;
}
virtual void MouseUp(const Point& inP) {
mMouseIsDown = false;
}
private:
bool mMouseIsDown;
Point mLastP;
};

class SelectionTool : public AbstractTool {
public:
SelectionTool() : mMouseIsDown(false) {}
virtual void MoveTo(const Point& inP) {
if(mMouseIsDown) {
mSelection.Set(mLastP, inP);
}
}
virtual void MouseDown(const Point& inP) {
mMouseIsDown = true;
mLastP = inP;
mSelection.Set(mLastP, inP);
}
virtual void MouseUp(const Point& inP) {
mMouseIsDown = false;
}
private:
bool mMouseIsDown;
Point mLastP;
Rectangle mSelection;
};

A client using the state pattern above could look like this:

class DrawingController {
public:
DrawingController() { selectPenTool(); } // Start with some tool.
void MoveTo(const Point& inP) {currentTool->MoveTo(inP)}
void MouseDown(const Point& inP) {currentTool->MouseDown(inP)}
void MouseUp(const Point& inP) {currentTool->MouseUp(inP)}

selectPenTool() {
currentTool.reset(new PenTool);
}

selectSelectionTool() {
currentTool.reset(new SelectionTool);
}

private:
std::auto_ptr currentTool;
};

The state of the drawing tool is thus represented entirely by an instance of AbstractTool. This makes it easy to add more tools and to keep their behavior localized to that subclass of AbstractTool.


DIAGRAM


+



---+ +




-+