Software Design Pattern By Example: Singleton

Explain Design Pattern in easy-to-understand example

Zhimin Zhan
5 min readOct 15, 2021

--

(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?

Analyse

1. Static Method

Clearly the getMachineId() is a static member or method, as its value returned is always the same (i.e. static).

Static member vs Instance member

class Car {
public:
Car(std::string make, std::string model);
};
class Sedan : Car {
public:
Sedan(std::string make, std::string model);
const static int number_of_wheels = 4;
};

With a static member, we can use it directly, without an instance (i.e. object).

std::cout << "Sedan has " << Sedan::number_of_wheels << " wheels\n";

As a comparison, here is how instance members are used.

Sedan my_car = new Sedan("Toyota", "Camry");    
Sedan wife_car = new Sedan("Honda", "Accord");
std::cout << my_car.make << "\n";
std::cout << wife_car.model <<…

--

--

Zhimin Zhan

Test automation & CT coach, author, speaker and award-winning software developer. Help teams succeed with Agile/DevOps by implementing real Continuous Testing.