Encapsulate concrete state pattern

From CSSEMediaWiki
Revision as of 03:14, 17 August 2008 by Tureiti Keith (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This pattern is in favour of encapsulation at the object level. The goal of this pattern is to reduce the impact of a designer's structural decisions on the flexibility of a class hierarchy.

The Approach

When designing a class, define properties rather than attributes; separate the data storage structure from the data access structure. Never access the data directly; instead, use accessor methods, both within and without the class. This provides the flexibility to modify the storage method of subclasses, and the method of storage of the base class as required.

An Example

The classic example given in [1] is that of a circle class. Figure 1 shows a single Circle class that defines the well known properties of a circle. Note that a single private attribute has been defined - the radius. From this, all the properties may be defined - access to this attribute is via the Radius property only.

Figure 1: A class capturing the properties of a circle

The encapsulate concrete state pattern allows a subclass to substitute the radius attribute with, for example, a diameter attribute. In this case the Radius and Diameter properties must be overridden. The Area and Circumference methods will require no modification, as they rely on a Circle's properties, not its attributes.

Criticisms

Personal tools