Software Design Pattern By Example: Singleton
Explain Design Pattern in easy-to-understand example
(I know the majority of this blog’s readers are testers or automation/DevOps engineers. This one is about software design.)
Design Patterns are good practices of Object-Oriented (OO) Software Design. Applying appropriate design patterns will help to design your software better. However, design patterns are not easy to master, it was the case for me, and my daughter as well when she started an IT degree at Uni. I wrote a series of articles to help her learn Design Patterns quickly. My approach is to use easy-to-understand exercises, which I believe is an easier way to master design patterns. This article’s pattern is Singleton.
The implementation language will be C++, but you are free to try with another OO language such as Java and Ruby.
Table of Contents:
· The Problem
· Analyse
· Sub-optimal Designs
∘ Static Method
∘ Static Member
· Singleton Pattern
∘ How does it work?
The Problem
In your application, the unique identifier of the machine (runs the program) is frequently used in the code. Considering getting a machine identifier is a relatively expensive operation (let’s say 1 second), how will you design the getMachineId()
function?