State pattern
|
A behavioral software design pattern, state pattern is used for computer programming to represent the state of an object. This is a clean way to 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 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; };
The state of the drawing tool is thus represented entirely by the class making it easy to add more tools and to keep their behavior localized to that subclass of AbstractTool
.
See also: Strategy pattern, Dynamic classification