chapter fourteen

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 collection 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 of 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 the code if it can treat an individual object the same way that 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.

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

14.1.1 Desired design features

14.1.2 Before using Singleton

14.1.3 After using Singleton

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 Composite

14.2.3 After using Composite

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 Decorator

14.3.3 After using Decorator

14.3.4 Decorator’s generic model

14.4 Summary