目录
创建型模式
单例模式
C++11语法规定,局部静态变量在第一次使用时进行初始化,如果存在多线程访问的情况,需要保证其初始化是线程安全性的。
底层原理:反汇编查看C++静态局部变量 ;说白了还是锁,只不过这段代码由编译器帮忙生成。
单例代码:
class Singleton {
public:
static Singleton& getInstance()
{
static Singleton s;
return s;
}
void work()
{
cout << "I am a Singleton" << endl;
}
private:
Singleton() {}
Singleton(const Singleton&other){}
~Singleton(){}
};
简单工厂
工厂生成产品,需要什么产品类型就传入参数。
缺点:如果新增产品,就需要修改工厂代码。
优点:简单。
class Product {
public:
virtual void show(){}
virtual ~Product() {}
};
class ProductA :public Product {
public:
void show() {
cout << "this is productA" << endl;
}
};
class ProductB :public Product {
public:
void show() {
cout << "this is productB" << endl;
}
};
class EasyFactory {
public:
static shared_ptr<Product> GetProduct(const string& type) {
if (type == "A")
{
return make_shared<ProductA>();
}
else if (type == "B")
{
return make_shared<ProductA>();
}
else {
return nullptr;
}
}
};
工厂方法
相对于简单工厂,优点是增加产品时,不需要修改工厂代码,而是新开一个工厂。
因为存在一个抽象工厂类,所以增加产品时,也需要增加一个生产这个产品的工厂类。
class Product {
public:
virtual void show(){}
virtual ~Product() {}
};
class ProductA :public Product {
public:
void show() {
cout << "this is productA" << endl;
}
};
class ProductB :public Product {
public:
void show() {
cout << "this is productB" << endl;
}
};
class Factory {
public:
virtual shared_ptr<Product> createProduct() = 0;
virtual ~Factory() {}
};
class FactoryA :public Factory
{
public:
shared_ptr<Product> createProduct()
{
return make_shared< ProductA>();
}
};
抽象工厂
抽象工厂通常会定义多个工厂方法,每个工厂方法用于创建一个特定类型的产品。
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <thread>
#include <mutex>
#include <functional>
using namespace std;
//抽象角色
class Character {
public:
virtual void show() = 0;
};
//抽象武器
class Weapon {
public:
virtual void show()= 0;
};
//魔法世界的角色
class MagicCharacter:public Character {
public:
void show() override
{
cout << "it's magic charactor" << endl;
}
};
//魔法世界的武器
class MagicWeapon:public Weapon {
public:
void show() override
{
cout << "it's magic weapon" << endl;
}
};
//科学世界的角色
class ScienceCharacter:public Character {
public:
void show() override
{
cout << "it's science charactor" << endl;
}
};
//科学世界的武器
class ScienceWeapon:public Weapon {
public:
void show() override
{
cout << "it's science weapon" << endl;
}
};
//抽象工厂
class AbstractFactory {
public:
virtual shared_ptr<Character> createCharacter() = 0;
virtual shared_ptr<Weapon> createWeapon() = 0;
};
//魔法世界工厂
class MagicFactory {
public:
shared_ptr<Character> createCharacter()
{
return make_shared<MagicCharacter>();
}
shared_ptr<Weapon> createWeapon()
{
return make_shared<MagicWeapon>();
}
};
//科学世界工厂
class ScienceFactory {
public:
shared_ptr<Character> createCharacter()
{
return make_shared<ScienceCharacter>();
}
shared_ptr<Weapon> createWeapon()
{
return make_shared<ScienceWeapon>();
}
};
int main()
{
shared_ptr<MagicFactory> sp_mf = make_shared<MagicFactory>();
auto mc = sp_mf->createCharacter();
auto mw = sp_mf->createWeapon();
mc->show();
mw->show();
shared_ptr<ScienceFactory> sp_sf = make_shared<ScienceFactory>();
auto sc = sp_sf->createCharacter();
auto sw = sp_sf->createWeapon();
sc->show();
sw->show();
}
结构型模式
装饰器模式
定义:以透明动态的方式来动态扩展对象的功能,也是继承关系的一种代替方案(合成复用原则:组合大于继承)。允许向一个现有的对象添加新的功能,同时又不改变其结构,是作为现有类的一个包装。
作用:在不想增加很多子类的情况下扩展。
如:你正在写一个软件,其中有一个功能是生成用户简介。用户简介包括用户的基本信息,如姓名、年龄等,以及一些可选的附加信息,比如兴趣爱好、工作经历等。你的软件需要支持动态地添加这些附加信息,而不改变原有的用户简介生成逻辑。这时候,装饰器模式就派上用场了。
如:我们定义了一个 Logger
接口,并实现了一个具体的基本日志记录器 BasicLogger
。再定义基础Logger的装饰器,然后我们定义了两个装饰器类 TimestampLogger
和 LogLevelLogger
,分别用于添加时间戳和日志级别。在 main
函数中,我们创建了基本日志记录器对象,并使用装饰器模式来动态地添加时间戳和日志级别。
示例代码:
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <thread>
#include <mutex>
#include <functional>
using namespace std;
class Logger {
public:
virtual void log(const string& msg) = 0;
~Logger() {}
};
class BaseLogger:public Logger {
public:
void log(const string& msg) override
{
cout << "BaseLogger:" << msg << endl;
}
};
class BaseDecorate :public Logger {
public:
BaseDecorate(shared_ptr<Logger> logger) :m_logger(logger) {}
void log(const string& msg) override
{
if (m_logger != nullptr)
{
m_logger->log(msg);
}
}
private:
shared_ptr<Logger> m_logger;
};
class TimeStampDecorate :public BaseDecorate
{
public:
TimeStampDecorate(shared_ptr<Logger> logger) :BaseDecorate(logger) {}
void log(const string& msg)
{
string msg2 = getTimeStamp() + ":" + msg;
BaseDecorate::log(msg2);
}
private:
string getTimeStamp()
{
return "2024-04-13 15:00:00";
}
};
class LogLevelDecorate :public BaseDecorate
{
public:
LogLevelDecorate(shared_ptr<Logger> logger) :BaseDecorate(logger) {}
void log(const string& msg)
{
string msg2 = string("[INFO]") + ":" + msg;
BaseDecorate::log(msg2);
}
};
int main()
{
shared_ptr<Logger> sp_bl = make_shared<BaseLogger>();
shared_ptr<BaseDecorate> sp_td = make_shared<TimeStampDecorate>(sp_bl);
sp_td->log("is's a timestamp log msg");
shared_ptr<BaseDecorate> sp_ld = make_shared<LogLevelDecorate>(sp_bl);
sp_ld->log("is's a loglevel log msg");
}
行为型模式
观察者模式
对象间的一对多关系,当一个对象状态发生改变时,依赖于它的对象都会得到通知并更新状态。
可以用于:消息队列系统、事件处理系统、数据库变更通知
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <thread>
#include <mutex>
#include <functional>
class Observer {
public:
virtual void update() = 0;
virtual ~Observer() {}
};
class ObserverA :public Observer {
public:
void update()
{
cout << "ObserverA update" << endl;
}
};
class ObserverB :public Observer {
public:
void update()
{
cout << "ObserverB update" << endl;
}
};
class Subject {
public:
virtual void attach(std::shared_ptr<Observer> observer) = 0;
virtual void detach(std::shared_ptr<Observer> observer) = 0;
virtual void notify() = 0;
private:
vector<std::shared_ptr<Observer>> observers;
};
class SubjectA {
public:
virtual void attach(std::shared_ptr<Observer> observer)
{
this->observers.push_back(observer);
}
virtual void detach(std::shared_ptr<Observer> observer)
{
auto it = std::find(observers.begin(), observers.end(), observer);
if (it != observers.end())
{
this->observers.erase(it);
}
}
virtual void notify()
{
for (auto &it : observers)
{
it->update();
}
}
private:
vector<std::shared_ptr<Observer>> observers;
};
int main()
{
shared_ptr<Observer> sp_OA = make_shared< ObserverA>();
shared_ptr<Observer> sp_OB = make_shared< ObserverB>();
shared_ptr<SubjectA> sp_SA = make_shared< SubjectA>();
sp_SA->attach(sp_OA);
sp_SA->attach(sp_OB);
sp_SA->notify();
sp_SA->detach(sp_OB);
sp_SA->notify();
}
策略模式
定义了一组算法,使得它们可以相互替代;让算法独立于使用他们的客户而独立变化。
优点:1、算法可以自由切换 2、避免使用多重条件判断 3、扩展性好。
class Strategy {
public:
virtual void exec() = 0;
virtual ~Strategy() {}
};
class StrategyA:public Strategy{
public:
void exec() override
{
cout << "exec A" << endl;
}
};
class StrategyB:public Strategy {
public:
void exec() override
{
cout << "exec B" << endl;
}
};
class Context {
private:
unique_ptr<Strategy> m_strategy;
public:
void setStrategy(unique_ptr<Strategy> strategy)
{
this->m_strategy = std::move(strategy);
}
void execStrategy()
{
if (this->m_strategy != nullptr)
{
this->m_strategy->exec();
}
else
{
cout << "Context's strategy is not set" << endl;
}
}
};
int main()
{
Context ctx;
unique_ptr<Strategy> sp_sa = make_unique< StrategyA>();
unique_ptr<Strategy> sp_sb = make_unique< StrategyB>();
ctx.setStrategy(std::move(sp_sa));
ctx.execStrategy();
ctx.setStrategy(std::move(sp_sb));
ctx.execStrategy();
return 0;
}