Summer_feeds
Just another WordPress.com weblog

State Pattern


State Pattern was discussed in detail. The example was discussed was regarding the telephone Booth.

The State pattern allows an object to change its behavior when its internal state changes. This pattern can be
observed in a vending machine. Vending machines have states based on the inventory, amount of currency
deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is
made, a vending machine will either deliver a product and no change, deliver a product and change, deliver
no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.


Vending machines best describes the functionality of states with the different user actions. User actions are inputted and states are taken in.

The state patten manipulation given with the common example is stated as below.

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 used as shown in the PenTool

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;
};

Advertisements

No Responses to “State Pattern”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: