STDIO Training

45 bundles
2 files3 days ago
2

Design Pattern - C++

Design Pattern - C++

Singleton

123456789101112131415161718192021222324252627282930313233343536373839404142#include <string>
#include <iostream>
using namespace std;

template <class T>
class Singleton {
private:
	static Singleton* instance;

	Singleton() {	}
	~Singleton() { }
public:
	static Singleton* getInstance() {
		return instance;
	}

	static void createInstance() {
		if (instance == nullptr) {
			instance = new Singleton();
			cout << "createInstance()" << endl;
		}
	}

	static void destroyInstance() {
		if (instance != nullptr) {
			delete instance;
			cout << "destroyInstance()" << endl;
		}
	}
};

Singleton* Singleton::instance = nullptr;

class ResourceManager {

};

int main() {
	Singleton<ResourceManager>::getInstance();

	return 0;
}

Factory

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849#include <string>
#include <iostream>
using namespace std;

class Duck;
class Chicken;
class Poutry {
	friend class Chicken;
	friend class Duck;
private:
	Poutry() { }
};

class Chicken : public Poutry {
public:
	Chicken() { }
};

class Duck : public Poutry {
public:
	Duck() { }
};

class PoutryFactory {
public:
	enum class Type {
		Chicken,
		Duck
	};

	static Poutry* create(Type type) {
		if (type == Type::Chicken)
			return new Chicken();
		else if (type == Type::Duck)
			return new Duck();

		return nullptr;
	}
};

class Management {

};

int main() {
	Poutry* p = PoutryFactory::create(PoutryFactory::Type::Chicken);

	return 0;
}