I'm reading the Design patterns book by the Gang of 4. Does a singleton use encapsulation? To me it would seem like yes, but i'm not 100% sure. Maybe I don't have a good understanding of encapsulation.
I'm not aware of a commonly agreed upon canonical definition of “encapsulation” but I believe that we can require at least the following.
An object's internals are encapsulated if it is not possible to transform the object into an invalid state (where its invariants are broken) via its public interface.
The public interface of the singleton class consists of a single static function
getInstance plus whatever interface the singleton object actually provides (this is not part of the pattern). The
getInstance function clearly cannot be used to bring anything in an invalid state because all it does is creating an instance via the default constructor and caching it in a global variable. Whether the actual (useful) interface of the class obeys encapsulation is up to its implementer. (Because the default constructor is private, it would in principle be allowed to construct an object in an invalid state but let's assume it doesn't.)
Considering the encapsulation of the rest of the class, the singleton pattern doesn't change anything about it. Or, as Robert Harvey has put it in the comments:
A Singleton doesn't bring any encapsulation to the table that a class doesn't already have. If a class has poor encapsulation, it will still have poor encapsulation after it is turned into a Singleton. A Singleton restricts a class to a single instance, and that's all that it does.
On the other hand, if your class was properly encapsulated in the first place, making it a singleton will not destroy that property. The singleton pattern violates another important principle, though. The single responsibility principle. It basically says that each component should do one job and do it well. (See the comments below for a somewhat different opinion.) The singleton pattern couples the business logic the class performs together with the rules who may create an instance of it and how many. This leads to tighter coupling between it and its consumers than desirable and makes especially testing needlessly hard. Nowadays the singleton is considered an antipattern by many. Much has been said about it so here is only one video from Google's Clean Code Talks on the topic: “Global State and Singletons” by Miško Hevery.
protected by user22815 Sep 26 '16 at 23:48
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?