Creational patterns

The Gang of Four list the following creational patterns:

Abstract Factory – an interface for creating families of related or dependent objects without specifying their concrete classes – the example the Gang of Four give is of an abstract factory that produces “abstract widgets” (ie display artefacts) that can then be subclassed to the particular look and feel of the display (the book shows its age by referring to Motif and Presentation Manager as choices, but the principle is unaltered). This pattern can be used when a system should be independent of how its products are created and represented, or when a library of software objects is needed but one wishes only to expose the interface and not the implementation.

Abstract Factories have a certain inflexibility though – to add a new output object it is necessary to change the interface and that also means changing all the concrete subclasses, as they have to match the interface of their abstract parent.

Builder – this separates the construction of a complex object from its representation, so allowing one construction process to create many different representations.

Builder software pattern
From wikipedia

Factory – defines an interface for creating an object but lets subclasses decide which class to instantiate.

Factory pattern in UML
From wikipedia

Prototype creates a prototypical instance and new objects are instantiated by copying this prototype.

The Gang of Four give an example of a musical score editor, which might create graphic elements to add to the score – but instead of the editor needing to have a subclass for every type of musical object to be added, it calls a parameterised clone method on a graphic (abstract) class that creates a copy of the concrete element sought.

UML for prototype pattern
From wikipedia

Singleton – a pattern to ensure that there is only one instance of a given class and that there is a universal point of access to it.

Often implemented using static methods in the real world:

class Spooler {
private spooler = 0
static Spooler getSpooler() {
if (spooler == 0)
spooler = new Spooler()
return spooler
protected Spooler() {
…some initialisation code…..

One thought on “Creational patterns

Comments are closed.