Design Patterns - Case Study, Chapter 2 - Formatting

Formatting

Formatting differs from structure. Formatting is a method of constructing a particular instance of the document's physical structure. This includes breaking text into lines, using hyphens, adjusting for margin widths, etc.

Problems and Constraints

  1. Balance between (formatting) quality, speed and storage space
  2. Keep formatting independent (uncoupled) from the document structure.

Solution and Pattern

A Compositor class will encapsulate the algorithm used to format a composition. Compositor is a subclass of the primitive object of the document's structure. A Compositor has an associated instance of a Composition object. When a Compositor runs its Compose, it iterates through each element of its associated Composition, and rearranges the structure by inserting Row and Column objects as needed.

The Compositor itself is an abstract class, allowing for derivative classes to use different formatting algorithms (such as double-spacing, wider margins, etc.)

The Strategy Pattern is used to accomplish this goal. A Strategy is a method of encapsulating multiple algorithms to be used based on a changing context. In this case, formatting should be different, depending on whether text, graphics, simple elements, etc., are being formatted.

Read more about this topic:  Design Patterns, Case Study, Chapter 2