Subject: [boost] Request for Feedback on the Singularity Design Pattern
From: Ben Robinson (icaretaker_at_[hidden])
Date: 2011-06-27 02:17:57
The Singularity Design Pattern seeks to address the three weaknesses of the
Singleton Design Pattern. Namely:
1) Lifetime: Singleton introduces lifetime management complexities (for a
detailed discussion, see Chapter 6 of Modern C++ Design by Andrei *
2) Initialization: Singleton restricts the class to the default constructor.
This makes Singleton unusable for classes which require non-default
3) Encapsulation: Singleton provides global access to the class. Some may
view this as a feature, but advocates of unit testing, dependency injection,
and context independent objects would disagree.
Singularity guarantees a single instance of a class, but does not suffer
from 1-3 above. Usage is as follows:
// Usage as a Factory:
typedef singularity<Horizon, single_threaded> HorizonSingularityType;
Horizon & horizonF = HorizonSingularityType::create(value, &event, event);
// Usage as a Base Class:
class Horizon : public singularity<Horizon, multi_threaded, global_access>
Horizon & horizonB = Horizon::create(value, &event, event);
Horizon & horizonC = Horizon::get();
The usage example above shows the three advantages of Singularity over
1) Singularity does not permit lazy initialization by design. The lifetime
of the single object is bounded by create() and destroy(), and this lifetime
is managed just like objects bounded by new() and delete().
2) Singularities of objects can be created using any available constructor
for that object.
3) Singularity prevents global access to the instance by default. However,
if this is required, or will help to transition from Singleton, a policy can
be supplied which enables a get() accessor to the instance.
It is also worth pointing out that thread safety is policy based, and both a
single_threaded, and multi_threaded policy are provided.
The source files are available here:
I look forward to your feedback.
Ben Robinson, Ph.D.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk