Design Patterns: Singleton Pattern in Modern C++

In software engineering, Creational Design Patterns deal with object creation mechanisms, i.e. try to create objects in a manner suitable to the situation. The basic or ordinary form of object creation could result in design problems or added complexity to the design. In this article of the Creational Design Patterns, we’re going to take a look at the much-hated & commonly asked design pattern in a programming interview. That is Singleton Design Pattern in Modern C++ which criticizes for its extensibility & testability. I will also cover the Multiton Design Pattern which quite contrary to Singleton.

By the way, If you haven’t check out my other articles on Creational Design Patterns, then here is the list:

  1. Factory
  2. Builder
  3. Prototype
  4. Singleton

The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like override, final, public(while inheritance) just to make code compact & consumable(most of the time) in single standard screen size.

I also prefer struct instead of class just to save line by not writing “public:” sometimes and also miss virtual destructor, constructor, copy constructor, prefix std::, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons.

Note:

  • If you stumbled here directly, then I would suggest you go through What is design pattern? first, even if it is trivial. I believe it will encourage you to explore more on this topic.
  • All of this code you encounter in this series of articles are compiled using C++20(though I have used Modern C++ features up to C++17 in most cases). So if you don’t have access to the latest compiler you can use https://wandbox.org/ which has preinstalled boost library as well.

Intent

To ensure one & only one instance of a class exist at any point in time.

  • The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object need to coordinate actions across the system.
  • So, essentially, the Singleton Design Pattern is nothing more than specifying a lifetime.

Singleton Design Pattern C++ Example

  • The motivation for using a Singleton Design Pattern is fairly obvious. Some components in our system only need to have a single instance. For example, a database that loads up from its constructor into memory & then gives out information about its contents. Once it’s loaded up you don’t really want more than one instance of it because there is no point.
  • And you also want to prevent your clients/API-users from making any additional copies of that object. Following is a trivial example of the Singleton Design Pattern in C++.
/* country.txt 
Japan
1000000
India
2000000
America
123500
*/
class SingletonDatabase {
    std::map<std::string, int32_t>  m_country;

    SingletonDatabase() {
        std::ifstream ifs("country.txt");

        std::string city, population;
        while (getline(ifs, city)) {
            getline(ifs, population);
            m_country[city] = stoi(population);
        }
    }

public:
    SingletonDatabase(SingletonDatabase const &) = delete;
    SingletonDatabase &operator=(SingletonDatabase const &) = delete;

    static SingletonDatabase &get() {
        static SingletonDatabase db;
        return db;
    }

    int32_t get_population(const std::string &name) { return m_country[name]; }
};

int main() {
    SingletonDatabase::get().get_population("Japan");
    return EXIT_SUCCESS;
}

Some of the things to note here from the design perspective are:

  1. Private constructor
  2. Deleted copy constructor & copy assignment operator
  3. Static object creation & static method to access

The Problem of Testability With Singleton

  • So we have our Singleton database and let’s suppose that we decide to use this database to do some research and we actually made a new class called a SingletonRecordFinder which is going to find the total population from the collection of city names provided in the argument as follow.
struct SingletonRecordFinder {
    static int32_t total_population(const vector<string>&   countries) {
        int32_t result = 0;
        for (auto &country : countries)
            result += SingletonDatabase::get().get_population(country);
        return result;
    }
};
  • But let’s suppose that we decide that we want to test the SingletonRecordFinder and this is where all the problems show up.
vector<string> countries= {"Japan", "India"}; // Strongly tied to data base entries
TEST(1000000 + 2000000, SingletonRecordFinder::total_population(countries));
  • Unfortunately, because we are strongly tied to the real database and there is no way to substitute this database. I have to use the values taken from the actual file. And when later on these entries change, your test will start failing as you may have not updated the code. And this going to be a continuous problem.
  • Moreover, this is not going to be a unit-test rather it is integration test as we are not only testing our code but also a production database which is not good design.
  • Surely there is a better way of actually implementing this particular construct so that we can still use the singleton but if need we can supply an alternative to the singleton implementation with some dummy data of our own.

Singleton Design Pattern With Dependency Injection

  • The problem that we’re encountering in the testing of the SingletonRecordFinder is to do with the fact that we have a dependency upon essentially the details of how a database provides its data because we’re depending directly on the singleton database and the fact that it’s a singleton.
  • So why don’t we use a little bit of dependency injection on an interface or abstract class!
struct Database { // Dependency 
    virtual int32_t get_population(const string& country) = 0;
};

class SingletonDatabase : Database {
    map<string, int32_t>    m_countries;

    SingletonDatabase() {
        ifstream ifs("countries.txt");

        string city, population;
        while (getline(ifs, city)) {
            getline(ifs, population);
            m_countries[city] = stoi(population);
        }
    }

public:
    SingletonDatabase(SingletonDatabase const &) = delete;
    SingletonDatabase &operator=(SingletonDatabase const &) = delete;

    static SingletonDatabase &get() {
        static SingletonDatabase db;
        return db;
    }

    int32_t get_population(const string &country) { return m_countries[country]; }
};

class DummyDatabase : public Database {
    map<string, int32_t>    m_countries;
public:
    DummyDatabase() : m_countries{{"alpha", 1}, {"beta", 2}, {"gamma", 3}} {}
    int32_t get_population(const string &country) { return m_countries[country]; }
};

/* Testing class ------------------------------------------------------------ */
class ConfigurableRecordFinder {
    Database&       m_db;  // Dependency Injection
public:
    ConfigurableRecordFinder(Database &db) : m_db{db} {}
    int32_t total_population(const vector<string> &countries) {
        int32_t result = 0;
        for (auto &country : countries)
            result += m_db.get_population(country);
        return result;
    }
};
/* ------------------------------------------------------------------------- */

int main() {
    DummyDatabase db;
    ConfigurableRecordFinder rf(db);
    rf.total_population({"Japan", "India", "America"});
    return EXIT_SUCCESS;
}

#cpp #cplusplus #design-patterns #design-thinking #computer-science #programming #coding #code-quality

What is GEEK

Buddha Community

Design Patterns: Singleton Pattern in Modern C++
Seamus  Quitzon

Seamus Quitzon

1601479980

Confused With Java Singleton Design Pattern? Have a Look at This Article.

What Is a Singleton Design Pattern?

  1. Singleton design pattern allows us to create only one instance of a class and make sure that there exists only one Object in JVM.
  2. Singleton class must have a public static method to get the instance of the class from anywhere in the application [from different classes, different packages, etc].
  3. Singleton class must have a private constructor to instantiate the object of the class.
  4. Singleton class must have a private static variable of the same class which is the only reference of the class[basically this variable will point to only Object of class].

Image for post

Singleton Design Pattern

All these different implementation methods lead to one goal that is having a single instance of a class at any given point of time in JVM. Let’s see different implementation approaches for the Singleton design pattern


1. Eager Initialization :

  1. This is the simplest implementation of the singleton design pattern class. In this method, the private static variable of the same class [reference] is assigned the object of class at the time of loading the class into the JVM memory.
  2. This type of implementation is applicable to the scenarios when we always want the instance of the class.

Let’s see the program to understand this …

package com.vikram;

	public class EagerSingleton {
	    //Only object created when class is loaded and theInstance is private static var pointing to it.
	    private static EagerSingleton theInstance = new EagerSingleton();

	    //private constructor
	    private EagerSingleton(){

	    }
	    //public method to return single instance of class .
	    public static EagerSingleton getInstance(){
	        return theInstance;
	    }
	}

Eager Initialization

#desing-pattern #classloading #singleton-pattern #singleton-design-pattern #java-singleton-pattern

Samanta  Moore

Samanta Moore

1623835440

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

Ari  Bogisich

Ari Bogisich

1596302220

Singleton Design Pattern in Modern C++

In software engineering, Creational Design Patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic or ordinary form of object creation could result in design problems or added complexity to the design. In this article of the Creational Design Patterns, we’re going to take a look at the much-hated & commonly asked design pattern in a programming interview. That is Singleton Design Pattern in Modern C++ which criticizes for its extensibility and testability. I will also cover the Multiton Design Pattern which quite contrary to Singleton.

The code snippets you see throughout this series of articles are simplified and unsophisticated. So you often see me not using keywords like overridefinalpublic(while inheritance) just to make code compact & consumable(most of the time) in single standard screen size. I also prefer struct instead of class just to save line by not writing “public:” sometimes and also miss virtual destructor, constructor, copy constructor, prefix std::, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons.

Note:

  • If you stumbled here directly, then I would suggest you go through, “What Is Design Pattern?” first, even if it is trivial. I believe it will encourage you to explore more on this topic.
  • All of this code you encounter in this series of articles are compiled using C++20(though I have used Modern C++ features up to C++17 in most cases). So if you don’t have access to the latest compiler you can use https://wandbox.org/ which has preinstalled boost library as well.

Intent

To create one & only one instance of a class at any point in time.

The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object need to coordinate actions across the system. So, essentially, the Singleton Design Pattern is nothing more than specifying a lifetime.

#design patterns #c++ #cplusplus #programming-c

Fannie  Zemlak

Fannie Zemlak

1597294800

Design Patterns: Exploring Factory Method in Modern C++

In software engineering, Creational Design Patterns deal with object creation mechanisms, i.e. try to create objects in a manner suitable to the situation. In addition to this basic or ordinary form of object creation could result in design problems or added complexity to the design.

Factory Design Pattern in C++ helps to mitigate this issue by creating objects using separate methods or polymorphic classes.

By the way, If you haven’t check out my other articles on Creational Design Patterns, then here is the list:

  1. Factory
  2. Builder
  3. Prototype
  4. Singleton

The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like override, final, public(while inheritance) just to make code compact & consumable (most of the time) in single standard screen size. I also prefer struct instead of class just to save line by not writing “public:” sometimes and also miss virtual destructor, constructor, copy constructor, prefix std::, deleting dynamic memory, intentionally.

I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons.

Note:

  • If you stumbled here directly, then I would suggest you go through What is design pattern? first, even if it is trivial. I believe it will encourage you to explore more on this topic.
  • All of this code you encounter in this series of articles are compiled using C++20(though I have used Modern C++ features up to C++17 in most cases). So if you don’t have access to the latest compiler you can use https://wandbox.org/ which has preinstalled boost library as well.

Intent

For the creation of wholesale objects unlike builder(which creates piecewise).

Motivation

  • Let say you have a Point class having x & y as co-ordinates which can be Cartesian or Polar coordinate as below:
struct Point {
    Point(float x, float y){ /*...*/ }         // Cartesian co-ordinates

    // Not OK: Cannot overload with same type of arguments
    // Point(float a, float b){ /*...*/ }      // Polar co-ordinates

    // ... Implementation
};
  • This isn’t possible as you might know you can not create two constructors with the same type of arguments.
  • Other way around is:
enum class PointType{ cartesian, polar };

class Point {
    Point(float a, float b, PointTypetype = PointType::cartesian) {
        if (type == PointType::cartesian) {
            x = a; b = y;
        }
        else {
            x = a * cos(b);
            y = a * sin(b);
        }
    }
};
  • But this isn’t a sophisticated way of doing this. Rather we should delegate separate instantiation to separate methods.

Factory Design Pattern Examples in C++

  • So as you can guess. We are going to mitigating constructor limitation by moving the initialization process from constructor to other structure. And we gonna be using the Factory Method for that.
  • And just as the name suggests it uses the method or member function to initialize the object.

Factory Method

enum class PointType { cartesian, polar };

class Point {
    float         m_x;
    float         m_y;
    PointType     m_type;

    // Private constructor, so that object can't be created directly
    Point(const float x, const float y, PointType t) : m_x{x}, m_y{y}, m_type{t} {}

  public:
    friend ostream &operator<<(ostream &os, const Point &obj) {
        return os << "x: " << obj.m_x << " y: " << obj.m_y;
    }
    static Point NewCartesian(float x, float y) {
        return {x, y, PointType::cartesian};
    }
    static Point NewPolar(float a, float b) {
        return {a * cos(b), a * sin(b), PointType::polar};
    }
};

int main() {
    // Point p{ 1,2 };  // will not work
    auto p = Point::NewPolar(5, M_PI_4);
    cout << p << endl;  // x: 3.53553 y: 3.53553
    return EXIT_SUCCESS;
}
  • As you can observe from the implementation. It actually disallows the use of constructor & forcing users to use static methods instead. And this is the essence of the Factory Method i.e. private constructor & static method.

Classical Factory Design Pattern

  • If you have dedicated code for construction then while not we move it to a dedicated class. And Just to do separation of concerns i.e. Single Responsibility Principle from SOLID design principles.
class Point {
    // ... as it is from above
    friend class PointFactory;
};

class PointFactory {
public:
    static Point NewCartesian(float x, float y) {
        return { x, y };
    }
    static Point NewPolar(float r, float theta) {
        return { r*cos(theta), r*sin(theta) };
    }
};
  • Mind that this is not the abstract factory this is a concrete factory. Making the PointFactory friend class of Point we have violated the Open-Closed Principle(OCP). As friend keyword itself contrary to OCP.

Inner Factory

  • There is a critical thing we missed in our Factory that there is no strong link between PointFactory & Point which confuses user to use Point just by seeing everything is private.
  • So rather than designing a factory outside the class. We can simply put it in the class which encourage users to use Factory.
  • Thus, we also serve the second problem which is breaking the Open-Closed Principle. And this will be somewhat more intuitive for the user to use Factory.
class Point {
    float   m_x;
    float   m_y;

    Point(float x, float y) : m_x(x), m_y(y) {}
public:
    struct Factory {
        static Point NewCartesian(float x, float y) { return { x,y }; }
        static Point NewPolar(float r, float theta) { return{ r*cos(theta), r*sin(theta) }; }
    };
};

int main() {
    auto p = Point::Factory::NewCartesian(2, 3);
    return EXIT_SUCCESS;
}

Abstract Factory

**Why **do we need an Abstract Factory?

  • C++ has the support of polymorphic object destruction using it’s base class’s virtual destructor. Similarly, equivalent support for creation & copying of objects is missing as С++ doesn’t support virtual constructor & copy constructors.
  • Moreover, you can’t create an object unless you know its static type, because the compiler must know the amount of space it needs to allocate. For the same reason, copy of an object also requires its type to known at compile-time.
struct Point {
    virtual ~Point(){ cout<<"~Point\n"; }
};

struct Point2D : Point {
    ~Point2D(){ cout<<"~Point2D\n"; }
};

struct Point3D : Point {
    ~Point3D(){ cout<<"~Point3D\n"; }
};

void who_am_i(Point *who) { // Not sure whether Point2D would be passed here or Point3D
    // How to `create` the object of same type i.e. pointed by who ?
    // How to `copy` object of same type i.e. pointed by who ?
    delete who; // you can delete object pointed by who, thanks to virtual destructor
}

Example of Abstract Factory Design Pattern

  • The Abstract Factory is useful in a situation that requires the creation of many different types of objects, all derived from a common base type.
  • The Abstract Factory defines a method for creating the objects, which subclasses can then override to specify the derived type that will be created. Thus, at run time, the appropriate Abstract Factory Method will be called depending upon the type of object referenced/pointed & return a base class pointer to a new instance of that object.
struct Point {
    virtual ~Point() = default;
    virtual unique_ptr<Point> create() = 0;
    virtual unique_ptr<Point> clone()    = 0;
};

struct Point2D : Point {
    unique_ptr<Point> create() { return make_unique<Point2D>(); }
    unique_ptr<Point> clone() { return make_unique<Point2D>(*this); }
};

struct Point3D : Point {
    unique_ptr<Point> create() { return make_unique<Point3D>(); }
    unique_ptr<Point> clone() { return make_unique<Point3D>(*this); }
};

void who_am_i(Point *who) {
    auto new_who       = who->create(); // `create` the object of same type i.e. pointed by who ?
    auto duplicate_who = who->clone();    // `copy` the object of same type i.e. pointed by who ?
    delete who;
}

Functional Approach to Factory Design Pattern using Modern C++

  • In our Abstract Factory example, we have followed the object-oriented approach but its equally possible nowadays to a more functional approach.
  • So, let’s build a similar kind of Factory without relying on polymorphic functionality as it might not suit some time-constrained application like an embedded system. Because the virtual table & dynamic dispatch mechanism may troll system during critical functionality.
  • This is pretty straight forward as it uses functional & lambda functions as follows:
struct Point { /* . . . */ };
struct Point2D : Point {/* . . . */};
struct Point3D : Point {/* . . . */};

class PointFunctionalFactory {
    map<PointType, function<unique_ptr<Point>() >>      m_factories;

public:
    PointFunctionalFactory() {
        m_factories[PointType::Point2D] = [] { return make_unique<Point2D>(); };
        m_factories[PointType::Point3D] = [] { return make_unique<Point3D>(); };
    }    
    unique_ptr<Point> create(PointType type) { return m_factories[type](); }  
};

int main() {
    PointFunctionalFactory pf;
    auto p2D = pf.create(PointType::Point2D);
    return EXIT_SUCCESS;
}
  • If you are thinking that we are over-engineering, then keep in mind that our object construction is simple here just to demonstrate the technique & so does our lambda function.
  • When your object representation increases, it requires a lot of methods to call in order to instantiate object properly, in such case you just need to modify lambda expression of the factory or introduce Builder Design Pattern.

Benefits of Factory Design Pattern

  1. Single point/class for different object creation. Thus easy to maintain & understand software.
  2. You can create the object without even knowing its type by using Abstract Factory.
  3. It provides great modularity. Imagine programming a video game, where you would like to add new types of enemies in the future, each of which has different AI functions and can update differently. By using a factory method, the controller of the program can call to the factory to create the enemies, without any dependency or knowledge of the actual types of enemies. Now, future developers can create new enemies, with new AI controls and new drawing member functions, add it to the factory, and create a level which calls the factory, asking for the enemies by name. Combine this method with an XML description of levels, and developers could create new levels without having to recompile their program. All this, thanks to the separation of creation of objects from the usage of objects.
  4. Allows you to change the design of your application more readily, this is known as loose coupling.

#cpp #cplusplus #programming #coding #design-patterns #design-thinking #codingbootcamp #factory-design-pattern

Proxy Design Pattern in Modern C++

In software engineering, Structural Design Patterns deal with the relationship between objects i.e. how objects/classes interact or build a relationship in a manner suitable to the situation. The Structural Design Patterns simplify the structure by identifying relationships. In this article of the Structural Design Patterns, we’re going to take a look at Proxy Design Pattern in C++ which dictates the way you access the object.

/!: This article has been originally published on my blog. If you are interested in receiving my latest articles, please sign up to my newsletter.

If you haven’t check out other Structural Design Patterns, then here is the list:

  1. Adapter
  2. Bridge
  3. Composite
  4. Decorator
  5. Facade
  6. Flyweight
  7. Proxy

The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like overridefinalpublic(while inheritance) just to make code compact & consumable(most of the time) in single standard screen size. I also prefer struct instead of class just to save line by not writing “public:” sometimes and also miss virtual destructor, constructor, copy constructor, prefix std::, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons.

Note:

  • If you stumbled here directly, then I would suggest you go through What is design pattern? first, even if it is trivial. I believe it will encourage you to explore more on this topic.
  • All of this code you encounter in this series of articles are compiled using C++20(though I have used Modern C++ features up to C++17 in most cases). So if you don’t have access to the latest compiler you can use https://wandbox.org/ which has preinstalled boost library as well.

#design-patterns #c-programming #coding #programming #cpp #c++