设计模式,C++实现
单例模式
#pragma once
template<typename T>
class Singleton {
public:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton(Singleton &&) = delete;
Singleton& operator=(Singleton &&) = delete;
static T& GetInstance() {
static T instance;
return instance;
}
};
class Client : public Singleton<Client> {
friend class Singleton<Client>; //谨记要声明友元类,否则无法调用Singleton 内的函数
protected:
Client() = default;
~Client() = default;
public:
static int GetValue() {
return GetInstance().value;
}
private:
int value = 0;
};
int main() {
const auto& client = Client::GetInstance();
auto value = client.GetValue();
}
抽象工厂模式
可以有多个工厂,每个工厂中可以生产各种类型的产品,每个产品也可以指定生产该产品门类下的任一品牌。
当抽象工厂模式如果只有一个组件的话(比如只有Component),其实是退化到了工厂方法模式,也就是没有了产品族的概念。
#pragma once
#include <iostream>
#include <memory>
/*抽象产品1*/
class Component {
public:
virtual ~Component() = default;
virtual void ComponentFun() = 0;
};
class ComponentA : public Component {
public:
void ComponentFun() {};
};
class ComponentB : public Component {
public:
void ComponentFun() {};
};
/*抽象产品2*/
class Element {
public:
virtual ~Element() = default;
virtual void ElementFun() = 0;
};
class ElementA : public Element{
public:
void ElementFun() {};
};
class ElementB : public Element{
public:
void ElementFun() {};
};
/*抽象工厂*/
class Factory {
public:
virtual std::shared_ptr<Component> CreateComponent() = 0;
virtual std::shared_ptr<Element> CreateElement() = 0;
};
class FactoryA : public Factory{
public:
std::shared_ptr<Component> CreateComponent() {
return std::make_shared<ComponentA>(); //注意,进行实例化时,需要实例化具体的对象,而非纯虚对象
}
std::shared_ptr<Element> CreateElement() {
return std::make_shared<ElementA>();
}
};
class FactoryB : public Factory {
public:
std::shared_ptr<Component> CreateComponent() {
return std::make_shared<ComponentB>();
}
std::shared_ptr<Element> CreateElement() {
return std::make_shared<ElementB>();
}
};
int main() {
std::shared_ptr<Factory> factory = std::make_shared<FactoryA>();
auto component_a = factory->CreateComponent();
auto element_a = factory->CreateElement();
component_a->ComponentFun();
element_a->ElementFun();
}