This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
CppPatterns/Singleton/main.cpp

43 lines
903 B
C++

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <mutex>
class Singleton {
private:
static Singleton *singleton;
static std::mutex mutex;
Singleton() = default;
public:
Singleton(const Singleton &other) = delete;
Singleton &operator=(const Singleton &) = delete;
static Singleton *GetInstance() {
std::lock_guard<std::mutex> lock(mutex);
if (singleton == nullptr) {
singleton = new Singleton();
}
return singleton;
}
};
Singleton *Singleton::singleton = nullptr;
std::mutex Singleton::mutex;
int main(int argc, char *argv[]) {
std::cout << "Singleton" << std::endl;
auto singleton1 = Singleton::GetInstance();
auto singleton2 = Singleton::GetInstance();
std::cout << std::setw(20) << "Singleton 1: " << singleton1 << std::endl;
std::cout << std::setw(20) << "Singleton 2: " << singleton2 << std::endl;
return EXIT_SUCCESS;
}