https://refactoring.guru/design-patterns/singleton
This week, I wanted to a find a source relating to software design and architectures. I’ve been curious about what I would need to know so I could write more robust and efficient code. One aspect of improving my code would be knowing how best to preserve available system memory and perform whatever tasks I need to within as few CPU cycles as I can. If my program is creating multiple instances of a class that are all doing the same thing, my code would be consuming more system resources than if I had one instance of a class that could be accessed by other parts of my code. The Singleton design pattern seeks to preserve memory consumption by utilizing a single static instance of a class that may be globally referenced from the rest of the program. To properly implement the Singleton, the constructor for your Singleton instance should be static and private. To get the instance, you would also need a public static creation method.
My homework for this week involves refactoring a class into the Singleton pattern, so I was especially interested in learning about it. I found this blog called The Refactoring Guru, and a post explaining the implementation of the Singleton, as well as the pros and cons from a design perspective. The Singleton design is useful when a program needs global access to a class, like when a program has a single attached database. The drawbacks of the Singleton approach, though, are that it does too many things at once in violation of the Single Responsibility Principle, and that it may compromise your program’s security because of a crucial class being accessed as a global variable.
The final paragraph of the blog post makes some comparisons between the Singleton design and two other software design patterns, Façade and Flyweight. Façade is a design pattern of constructing a simple user interface with a complicated backend. This design pattern offers a sort of “black box” functionality to users, having a simple frontend to interact with without the need to inform users about the inner implementations of the software. The practical example given for a Façade software design is a video encoding service that accepts video files from the user as input and returns the same file encoded in a new file format. The user would only need to interact with the function that accepts a file and a desired file type as parameters, without needing to access the methods within the program that perform operations on the input file.
This blog includes helpful illustrations and pseudocode to explain multiple different software design patterns. I’ve been needing more resources on broader software structure and design rather than individual blocks of code, and I’m happy that I found this website.
From the blog CS@Worcester – Michael's Programming Blog by mikesprogrammingblog and used with permission of the author. All other rights reserved by the author.