State pattern |
A Behavioral_pattern software design pattern, state pattern is used in computer programming to represent the state of an object (computer science). This is a clean way for an object to partially change its type at runtime.
For example, in a drawing program there could be an abstract interface representing a tool, then concrete instances of that class could each represent a kind of tool. When the user selects a different tool, the appropriate tool would be instance (programming).
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; };
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.
=See also=
|
|