How to show a Singleton relationship in a class diagram

ahj picture ahj · Feb 29, 2012 · Viewed 24.3k times · Source

If a class contains pointer to a singleton class, can it beaggregation?

To my understanding it cannot be a has-a relationship since the class does not make an instance of the singleton class, it is just using it like association relationship.

Answer

Uffe picture Uffe · Mar 6, 2012

The title doesn't make 100% complete sense as written. There are singleton classes, but there aren't really singleton relationships. Any relationship can be assigned a multiplicity at either end, so if you mean one-to-one relationships, all you do is assign multiplicity 1 at both ends.

Classes can also have multiplicities. You don't often see this used, except in one case: singletons.

When it comes to A having or containing or referencing B, there are basically three levels of tightness in UML.

Aggregation (unfilled rhomboid arrow head) implies that the containment is not exclusive and that the contained object does not share any aspect of its lifecycle with the containing object. In implementation, this is typically a pointer.

Composition (filled rhomboid arrow head) implies that the contained object gets destroyed when the containing object does. Getting this to work usually means that the containment is exclusive. In implementation, this is often a pointer whose destructor is called in the destructor of the containing class (although it may not be created in the constructor of the containing class).

Directed association or member attribute (same thing in UML) implies that the contained object is part of the state, or a constituent if you will, of the containing object. In implementation, this typically means that the reference is not a pointer, or if it is that the contained object is co-created and -destroyed with the containing object.

Aggregation of a singleton is perfectly permissible (even from several different classes), because aggregation is by definition non-exclusive.

Composition is a bit iffy, unless the containing class is also a singleton.

Attribute / directed association is most likely wrong. If the containing class is a singleton, it doesn't make any sense to make the contained class a singleton as well since that's implied. And if the contained class is used as a member in two different classes, it cannot be a singleton.

In addition to the above, you can also of course add as many Usage relationships as you wish. This is common in all design, and implies that the class at the source end of the relationship calls methods in the class at the target end.

enter image description here