Yesterday I was reading “Design Patterns: Elements of Reusable Object-Oriented Software” book and found an interesting concept hence just wanted to share... Being in C++ for years, I have never had a chance to work with State Pattern; well its ok there is always room for improvement.
With no further ado, here it is…
Consider a case where you want to change an Object’s Class during Run-Time. This example could explain the need for it:
If you have an account, and don't use the account for a long time, or close it, it may change to a closed account. The information you have in a closed account may be very different from that in an open account. There may be some shared information, primarily the id of the account. Implementation would be base class of account, with two inherited classes, open and closed account. Now it would be useful to be able to change an open account to closed account (Change type) at runtime without having to do extra work. It should be possible to implement invariants as to what transitions are possible. Open to Closed but not Closed to Open.
State Pattern comes handy in solving such problems. When you find some free time, read more at State Patterns! If you are new to Design Patterns and want to learn more, the above said book is the best bet.