Seeing as we’ve started learning about design patters in class recently, I decided I’d explore a pattern further in depth. Seeing as the singleton pattern was the last covered in class it was the one I chose. Where most other sources would just condemn it as a bad practice, the article linked above does a good job of exemplifying both the pros and the cons of using the singleton design pattern. One of the pros, something I learned as well, was how singleton classes can save memory by using lazy instantiation. Opting not to assign memory to the variable until called; this method can create errors as well. If multiple threads access the instance at the same time it will create multiple instances of the singleton class. There are synchronizing techniques to get around the issue but it’d most likely be easier to use static initialization. In static initialization, memory is allocated when the variable is declared. The only difference this makes in the code is moving the creation of the object to where the variable is being declared. Inheritance with singleton classes seems straightforward enough. Any class inheriting from it will create more than one instance of the class thus violation the principle that only one instance can exist. However, if you wanted multiple singletons to inherit the same behavior, the code could be provided in an abstract class. Although this may seem purely a shortcoming, it does prove itself when compared to static classes inability to work from interfaces. One of the other major drawbacks that I learned about was that singleton classes couldn’t accept parameters which contributes to their limited flexibility.
The singleton pattern has me a bit conflicted with its use in java. Although it seems like an easy way to create global variables in java, many of its drawbacks seem very limiting or painstaking with more complicated programs. The linked article does, however, do a great job of showing and explaining how to create singleton classes and will differently be my go to for a reference. Reading it was a great auxiliary to the lectures given in class. Seeing how singletons work (and don’t), in depth, has also raised my confidence with working with them. I’m sure that having a complete understanding of this design pattern will be useful as a tool to compare and understand the behaviors of other patterns.