Question about Singleton

Aug 5, 2012 at 4:47 PM

I copy paste a question about understanding the DPL Singleton pattern script


Question on DPL Singleton

Is this what you had in mind for the analyzer searching for the pattern in C# code: parse the code to find classes with private constructors and that will return an instance if its exists otherwise creates one? Also, in the DPL definition of singleton, CALLER is defined to not be a part of any class - but methods in any class can create an instance of a singleton.


When you implement Design patterns, you  have 2 things:

1. The inner pattern restrictions. Whichever tweaks you try to apply to bind the patterns toward your goals, the pattern is protected by design: you simply cannot.

2. The usage conventions: the pattern is defining a kind of best practice; if you break it, it is at your won risk, because the apttern will be considered invalid and therfore won't respect its promises.

So DPL catch both points (whereas UML often cannot catch the 2 point).

 CALLER([S]) = {getInstance} use the 2) philosophy. [S] means "constructor".

if the constructor is public but anyway all classes are calling the getInstance only and never the constructor directrly it's fine, it is a Singleton. Then DPL will recommand to make the constructor private (in later versions). If, however, we have getInstance1 and getInstance2 returning a Singleton, then we're not really in a Singleton, even if the constructor is private.

So CALLER([S]) = {getInstance}  is finally a more permissive and general rule than the private constructor.