Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mark a class as a singleton in UML?

Tags:

I have an UML diagram on which I want to mark some classes as singletons (because they are). How do I do that? Do I invent a new stereotype or do I just add a comment or are there some existing means to do that?

like image 418
Alexander Kulyakhtin Avatar asked Dec 05 '11 14:12

Alexander Kulyakhtin


People also ask

How to specify a class is a singleton in UML?

To specify that a class is a singleton, you can write a constraint in between braces: { number of instances = 1 }. This constraint should be put in a constraints compartment in the class rectangle. The UML 2.5 specification, §7.6.4 defines the notation for constraints in general and §9.2.4 specifies how to show the constraints of a classifier:

How do you mark a class with a 1 in UML?

In a UML diagram, such a class can be marked with a ‘1’ in the upper right corner of the name compartment. See Figure 16.17. Figure 16.17 Showing a singleton.

How does classic Singleton create an instance of a class?

Classic Singleton creates an instance only if there is no instance created so far; otherwise, it will return the instance that is already created. Let’s take a look at the below code. Here, in the __new__ method, we will check whether an instance is created or not. If created, it will return the instance; otherwise, it will create a new instance.

What happens when we subclass a singleton class in Java?

Let’s check what happens when we subclass a singleton class. Here, you can see that SingletonChild has the same instance of SingletonClass and also shares the same state. But there are scenarios, where we need a different instance, but should share the same state. This state sharing can be achieved using Borg singleton.


2 Answers

"What will most clearly represent the concept to your reader."

There is a reasonable example of the basic appearance over on Wikipedia. It shows a private constructor and a public getInstance() method that returns an object of type Singleton. I'd also find a stereotype to be a perfectly reasonable way to make it explicit without requiring your reader to parse the details of the class object.

like image 111
David H. Clements Avatar answered Oct 27 '22 01:10

David H. Clements


Craig Larman's "Applying UML and Patterns" book (3rd edition) gives the following notation for a sequence diagram:

Note that it implies that before calling doA the :Register object manages to get access to the singleton via the standard way, e.g., getInstance(). This makes the diagram more agile.

For a class diagram:

like image 37
Fuhrmanator Avatar answered Oct 27 '22 01:10

Fuhrmanator