Understanding and Implementing the Singleton Pattern

Understanding and Implementing the Singleton Pattern

Welcome to the first lesson in our Creational Design Patterns course. We are starting with a powerful and widely used pattern: the Singleton Pattern. This pattern helps ensure that a class has only one instance and provides a global point of access to it. Understanding this pattern is a fantastic first step on your journey to mastering creational design patterns.

What You'll Learn

In this lesson, you'll learn how to implement the Singleton Pattern in C++. We'll cover the following key points:

  1. Creating a Singleton Class: We'll explore how to construct a Singleton class, ensuring it has exactly one instance.
  2. Accessing the Singleton Instance: You'll learn how to create a global access point to this single instance.

Here's a sneak peek of the code you'll be working with:

C++
#include <iostream>
#include <string>

class Logger {
public:
    // Static method to access the single instance
    static Logger& getInstance() {
        static Logger instance; // The single instance of the Logger
        return instance;
    }

    // Log a message to the console
    void log(const std::string& message) {
        std::cout << message << std::endl;
    }

private:
    Logger() {} // Private constructor to prevent external instantiation
    Logger(const Logger&) = delete; // Deleted copy constructor
    void operator=(const Logger&) = delete; // Deleted assignment operator
};

int main() {
    // Access the Logger instance and log a message
    Logger::getInstance().log("Singleton pattern example with Logger.");
    return 0;
}

In this snippet, you can see how we ensure that only one Logger instance is created and how we access it globally. We achieve this by defining a getInstance method that returns a reference to the single instance of the Logger class.

These are the essential parts of the Singleton Pattern:

  • Private Constructor: The constructor is private to prevent external instantiation of the class.
  • Static Method: A static getInstance method is used to access the single instance of the class without creating a new object.
  • Static Member: A static member variable holds a single instance of the class.
  • Deleted Copy Constructor and Assignment Operator: To prevent copying the instance, we delete the copy constructor and assignment operator.

Advantages and Disadvantages of the Singleton Pattern

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal