#include <iostream>
#include <memory>
#include <functional>
#include <vector>
#include <string>
// Singleton
class Singleton {
static Singleton& instance() {
static Singleton inst;
return inst;
}
Singleton() = default;
public:
static Singleton& get() { return instance(); }
void doSomething() { std::cout << "Singleton doing something\n"; }
};
// Observer
class Observer {
public:
virtual ~Observer() = default;
virtual void update(const std::string& event) = 0;
};
class Subject {
std::vector<std::shared_ptr<Observer>> observers;
public:
void subscribe(std::shared_ptr<Observer> obs) { observers.push_back(obs); }
void notify(const std::string& event) {
for (auto& obs : observers) obs->update(event);
}
};
// Factory
template<typename T>
class Factory {
using Creator = std::function<std::unique_ptr<T>()>;
std::map<std::string, Creator> creators;
public:
void registerType(const std::string& name, Creator creator) {
creators[name] = creator;
}
std::unique_ptr<T> create(const std::string& name) {
return creatorsname;
}
};
// Strategy
class SortStrategy {
public:
virtual ~SortStrategy() = default;
virtual void sort(std::vector<int>& data) = 0;
};
class BubbleSort : public SortStrategy {
void sort(std::vector<int>& data) override {
std::cout << "Bubble sort\n";
for (size_t i = 0; i < data.size(); ++i)
for (size_t j = 0; j < data.size()-i-1; ++j)
if (data[j] > data[j+1]) std::swap(data[j], data[j+1]);
}
};
class QuickSort : public SortStrategy {
void sort(std::vector<int>& data) override { std::cout << "Quick sort\n"; }
};
class Sorter {
std::unique_ptr<SortStrategy> strategy;
public:
void setStrategy(std::unique_ptr<SortStrategy> s) { strategy = std::move(s); }
void sort(std::vector<int>& data) { strategy->sort(data); }
};
int main() {
Singleton::get().doSomething();
markdown
Subject subject;
auto obs = std::make_shared<Observer>();
Sorter sorter;
sorter.setStrategy(std::make_unique<QuickSort>());
std::vector<int> data = {5, 3, 1, 4, 2};
sorter.sort(data);
return 0;
}