原文链接 https://www.cnblogs.com/chengjundu/p/8473564.html
1、工厂模式
通过一个公共的接口创建对象,一般在创建复杂对象时使用
#include <iostream>
typedef enum {
tankType_56,
tankType_96,
tankType_num
}tankType;
//抽象产品类
class Tank {
public:
virtual const string& type() = 0;
};
//具体的产品类
class Tank_96 : public Tank {
public:
Tank_96 : Tank(), m_strType("tank96") {
}
const string& type() override {
cout<<m_strType.data()<<endl;
return m_strtype;
}
private:
string m_strType;
};
//具体的产品类
class Tank_56 : public Tank {
public:
Tank_56 : Tank(), m_strType("tank56") {
}
const string& type() override {
cout<<m_strtype.data()<<endl;
return m_strType;
}
private:
string m_strType;
};
class TankFactory {
public:
Tank* creatTank(tankType type) {
switch(type) {
case tankType_56:
return new Tank_56();
case tankType_96:
return new Tank_96();
default:
return nullptr;
}
}
};
int main() {
TankFactory factory = new TankFactory();
Tank* tank56 = factory->creakTank(tankType_56);
tank56->type();
Tank* tank96 = factory->creakTank(tankType_96);
tank96->type();
delete tank56;
tank56 = nullptr;
delete tank96;
tank96 = nullptr;
delete factory;
factory = nullptr;
return 0;
}
2、单例模式
保证一个类仅有一个实例化对象,并且提供一个可以访问它的全局结构。单例模式分为懒汉模式和饿汉模式
2.1 懒汉模式
不到万不得已不会去实例化类,即在第一次使用到类实例的时候才会去实例化一个对象,在访问量较小,甚至可能不访问的时候使用懒汉模式,以时间换空间
1、非线程安全的懒汉单例模式
//构造函数私有,且不能通过拷贝构造、赋值运算符实例化对象
class Singleton {
public:
static Singleton* getInstance();
~Singleton(){};
private:
Singleton(){};
Singleton(const Singleton& obj) = delete;
Singleton& operator=(const Singleton& obj) = delete;
static Singleton* m_pSingleton;
};
Singleton* Singleton::mpSingleton = nullptr;
Singleton* Singleton::getInstance() {
if (m_pSingleton == nullptr) {
m_pSingleton = new Singleton();
}
return m_pSingleton;
}
2、线程安全的懒汉单例模式
//构造函数私有,且不能通过拷贝构造、赋值运算符实例化对象
std::mutex mx;
class Singleton {
public:
static Singleton* getInstance();
~Singleton(){};
private:
Singleton(){};
Singleton(const Singleton& obj) = delete;
Singleton& operator=(const Singleton& obj) = delete;
static Singleton* m_pSingleton;
};
Singleton* Singleton::m_pSingleton = nullptr;
Singleton* Singleton::getInstance() {
if (m_pSingleton == nullptr) {
mx.lock();
if (m_pSingleton == nullptr) {
m_pSingleton = new Singleton();
}
mx.unlock;
}
return m_pSingleton;
}
2.2 饿汉模式
饿了要饥不择食,在类定义时就进行实例化对象。在访问量较大,或者可能访问的线程较多时采用饿汉模式实现,可以实现更好的性能,以空间换时间
//线程安全,注意一定要在合适的地方进行释放
class Singleton {
public:
static Singleton* getInstance();
~Singleton(){};
private:
Singleton(){};
Singleton(const Singleton& obj) = delete;
Singleton& operator=(const Singleton& obj) = delete;
static Singleton* m_pSingleton;
};
Singleton* Singleton::m_pSingleton = new Singleton();
Singleton* Singleton::getInstance() {
return m_pSingleton;
}