Card 02/ 05

ComparisonDifficulty: Intermediate1 min

Prototype vs Singleton vs a Plain Constructor

Copy a configured object, share one object, or make a new one the ordinary way.

Prototype, Singleton and a plain constructor each answer a different question about where an object comes from. Prototype answers "copy a configured one" when setting an object up is costly or its class is unknown. Singleton answers "share the only one" when exactly one object of a class may exist. A constructor answers "make a new one" when nothing about creation varies, and it is the default the other five patterns have to beat. This card sets those answers beside Factory Method, Abstract Factory and Builder, and ends at a flowchart for all six.

The question each one answers
ChoiceThe question it answersThe sign in the problem
PrototypeCan a new object start as a copy of a configured one?Set-up is costly or long, or only an existing object of the class is at hand
SingletonMust every caller get the same one object?A second instance would be a bug and not only a waste
ConstructorDoes anything about creating the object vary?No: one class, its fields known, no family and no optional steps

The flowchart asks the questions in an order that reaches the constructor fastest when nothing varies. Each "no" moves one question down, and the last "no" is the constructor.

Choosing how an object is created

The Singleton box offers an alternative because a global access point hides dependencies and carries state between tests: one object created at start-up and passed to the code that needs it gives the same single instance without the hidden state. Prototype and Singleton are opposites in one respect, since Prototype gives every caller a new object and Singleton gives every caller the same one.