Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+17 votes
asked in CSC305 Fall 2022 by (1 point)

1 Answer

+7 votes
 
Best answer

The singleton pattern ensures only 1 instance of an object, and it is globally accessible. This can save memory and space, because the same instance is being referenced instead of creating a new object at every request for information. It then very easy to use because the globally accessible object is readily available.

However, making something a global variable creates hidden dependancies and so it is not easy to test the code, and it can be difficult to track.

https://www.freecodecamp.org/news/singleton-design-pattern-pros-and-cons-e10f98e23d63/
https://www.linkedin.com/pulse/singleton-pros-cons-rainer-grimm
^^I found these helpful to understand the gist of the cons.

answered by (1 point)
selected by
+8

Mostly correct, but the advantages aren't about saving memory/space... references to the same object barely take any space anyway.

Instead, it's more about:

A) making sure that every part of your app is using the same object, rather than potentially having bugs where different parts of your app are modifying different objects, thinking they are the same, and

B) making it easy to access that singleton object from anywhere in your application, without having to pass a reference to the object into any method/class that might want to interact with the object.

In terms of cons:

A) like with "global variables" more generally, it becomes hard to tell which classes in your code actually need access to the object, since any class can easily access it. This can potentially make your overall project structure harder to understand, and

2) It doesn't always lead to good extensibility, because in some cases you'll realize you do want to support multiple objects of that type, and then you'll have to remove the Singleton pattern later.

...