Encapsulate concrete state pattern

From CSSEMediaWiki
Jump to: navigation, search

This axiom is contained in Pattern Languages of Program Design and republished in Ken Auer 1995.

The encapsulate concrete state pattern favours 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.

Contents

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 PLoP 1995 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 MyCircle (Fig. 1) to instead describe a Circle's properties using a diameter attribute. In this case the Radius and Diameter properties must be overridden by the subclass. The Area and Circumference methods will require no modification, as they rely on a Circle's properties, not its attributes.

Criticisms

Performance Constraints

In time critical systems, without sufficient compiler support for this pattern, this approach can be of detriment to the performance of the system. In, for example, a digital signal processor, performance is paramount. In this situation an additional operation purely for the purposes of data access is difficult to justify [1].

Cyclic Dependencies

A designer considering this pattern must be weary of forming cyclic dependencies. In the example of Fig. 1 above, a designer need only to define the radius in terms of the diameter, and the diameter in terms of the radius to form a cyclic dependency (see Identify message layers pattern).

References

  1. ^ Extrapolated from a lecture by Dr Allan Murray of Tait Electronics Limited on the constraints of DSP implementation

See Also

Personal tools