14 The Singleton, Composite, and Decorator Design Patterns

 

This chapter covers

  • The Singleton Design Pattern
  • The Composite Design Pattern
  • The Decorator Design Pattern

This chapter’s design patterns provide models for solving architecture problems where we must manage a collection of one or more objects so that the it behaves in a unified way. Applying the right design pattern can simplify the application’s code that works with the objects, and it can also make the code more flexible.

The Singleton Design Pattern models the simplest case of a collection with only one object. Only one instance of its class, the singleton object, can exist during the application’s run time.

The Composite Design Pattern provides a model for an application that manages objects stored in a hierarchical tree structure. The application can greatly reduce the complexity of its code if it can treat an individual object the same way it treats a composite of objects.

We may want our application to add responsibilities to an object in the form of attributes and behaviors at run time but without changing the object’s code. These additional responsibilities, in the form of objects, are called “decorations” by the Decorator Design Pattern, which provides a model that handles an object’s decorations in a flexible manner.

NOTE

Be sure to read the introduction to part 4 for important information about design patterns in general and to learn how this and subsequent chapters teach each pattern.

14.1 The Singleton Design Pattern ensures a class has only one object

14.1.1 Desired design features

14.1.2 Before using the Singleton Design Pattern

14.1.3 After using the Singleton Design Pattern

14.1.4 Singleton’s generic model

14.2 The Composite Design Pattern treats individual and composite objects uniformly

14.2.1 Desired design features

14.2.2 Before using the Composite Design Pattern

14.2.3 After using the Composite Design Pattern

14.2.4 Composite’s generic model

14.3 The Decorator Design Pattern dynamically adds object responsibilities

14.3.1 Desired design features

14.3.2 Before using the Decorator Design Pattern

14.3.3 After using the Decorator Design Pattern

14.3.4 Decorator’s generic model