Change an Object's Class at Run-Time (State Pattern)

Source: comp.object
Date: 28-Sep-97

Related Sites


o-< Problem:
  1. How can you change the class of an object at run-time?
  2. How can you model a finite state machine using OO techniques?


o-< Nick Leaton wrote:

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.


o-< Robert C. Martin replied:

There is a specific design pattern that solves this problem. It is called "State"; and can be found in the GOF book Design Patterns, Gamma, et. al., Addison Wesley, 1994. [This book is a MUST READ -YS]

           ^                    A
           |                    |
           |              +-----+-----+
           |              |           |
           |       |OpenState|    |ClosedState|
           |           |               |
Account contains a base class named AccountState. There are two subclasses of AccountState named OpenState and ClosedState. Each of these contain a reference back to the |Account|.

This allows methods of Account that are affected by the state to be delegated to the contained state object. The state object then calls the appropriate functions in the Account object.


o-< More Info:

Vince Huston, A short description of the State pattern

Graham Perkins, A longer description of the State pattern

Patterns Home Page