设计模式 | 忙不迭 千年碑易拓 却难拓你的美
Cobb 647 0

单例模式 Singleton

几种单例模式的写法

/*
OOP设计模式 - 23种

设计模式一01: 单例模式  Singleton
日志类
*/

class Logger
{
public:
    // 2. 返回唯一对象
    static Logger* GetInstance()
    {
        static Logger logger;
        return &logger;
    }
private:
    // 1. 私有化构造函数
    Logger()
    {

    }

    // 3. 干掉拷贝构造
    Logger(const Logger&) = delete;
};
int main()
{
    Logger *logger = Logger::GetInstance();
    //Logger logger_b = *logger;
}

工厂模式

软件设计原则: 1,高内聚(自己能完成的事不依赖第三方),低耦合(方法之间尽量减少互相依赖) 2,开闭原则,多扩展开放,对修改关闭。

起始->简单工厂

缺点:createproduct接口永远无法修改关闭,而且越写越多,不符合设计开闭原则。

#include <string>
#include <iostream>
using namespace std;
enum objtype
{
    huawei,
    xiaomi,
    vivo,
};
class phone
{
public:
    phone(string name):name_(name){}
    void show() const {cout<<"name"<<name_<<endl;}
protected:
    string name_;
};
class huaweiphone : public phone
{
public:
    huaweiphone(string name):phone(name){}
};
class xiaomiphone:public phone
{
public:
    xiaomiphone(string name):phone(name){}
};
class simplefactor
{
public:
    phone* createprotuct(objtype type)
    {
        switch (type)
        {
            case huawei:
                return new huaweiphone("荣耀");
            case xiaomi:
                return new xiaomiphone("note2");
            default:
                break;
        }
        return nullptr;
    }
};
int main()
{
    simplefactor factory;
    phone* p = factory.createprotuct(huawei);
    p->show();
    p = factory.createprotuct(xiaomi);
    p->show();
    return 0;
}

进化->工厂方法

缺点:如果增加新的产品,就得有更多的工厂被创建出来。但实际上,有关联关系的产品,是可以在同一个工厂被创建出来的。

#include <string>
#include <iostream>
using namespace std;
enum objtype
{
    huawei,
    xiaomi,
    vivo,
};

class phone
{
public:
    phone(string name):name_(name){}
    void show() const {cout<<"name"<<name_<<endl;}
protected:
    string name_;
};

class huaweiphone : public phone
{
public:
    huaweiphone(string name):phone(name){}
};

class xiaomiphone:public phone
{
public:
    xiaomiphone(string name):phone(name){}
};

class simplefactor
{
public:
    virtual phone* createprotuct() = 0;
};

class huaweifactor : public simplefactor
{
public:
    phone* createprotuct()
    {
        return new huaweiphone("荣耀");
    }
};
class xiaomifactor : public simplefactor
{
public:
    phone* createprotuct()
    {
        return new huaweiphone("note2");
    }
};

int main()
{
    huaweifactor factor;


}

进化->抽象工厂

优点:一组有关联关系的产品,统一放在一个抽象工厂中去创建,防止产生过多的工厂类

缺点:当一个品种需要增加方法时。所有品种的工厂都要实现该方法,否则会成为抽象类。

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

class phone
{
public:
    phone(string name):name_(name){}
    void show() const {cout<<"name"<<name_<<endl;}
protected:
    string name_;
};

class computer
{
public:
    computer(string name):name_(name){}
    void show() const {cout<<"name"<<name_<<endl;}
protected:
    string name_;
};

class huaweiphone : public phone
{
public:
    huaweiphone(string name):phone(name){}
};

class xiaomiphone:public phone
{
public:
    xiaomiphone(string name):phone(name){}
};

class huaweicomputer : public computer
{
public:
   huaweicomputer(string name):computer(name){}
};

class xiaomicomputer:public computer
{
public:
    xiaomicomputer(string name):computer(name){}
};

class abstractfactory
{
    public:
    virtual phone* createphone() = 0;
    virtual computer* createcomputer() = 0;
};

class huaweifactor : public abstractfactory
{

    phone* createphone()
    {
        return new huaweiphone("荣耀");
    }
    computer* createcomputer()
    {
        return new huaweicomputer("荣耀2");
    }
};

class xiaomifactor : public abstractfactory
{

    phone* createphone()
    {
        return new huaweiphone("小米");
    }
    computer* createcomputer()
    {
        return new huaweicomputer("小米2");
    }
};

int main()
{

    abstractfactory* ph = nullptr;
    phone* p = nullptr;
    computer* c = nullptr;

    ph = new huaweifactor();
    p = ph->createphone();
    p->show();
    c = ph->createcomputer();
    c->show();

    ph = new xiaomifactor();
    p = ph->createphone();
    p->show();
    c = ph->createcomputer();
    c->show();

}

观察者模式



#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

// 监听者基类
class Listener
{
public:
    Listener(string name) :name_(name) {}
    // 等待event事件发生,然后处理自己关心的事件
    virtual void HandleMsg(int event) = 0;
protected:
    string name_;
};

class Lis1 : public Listener
{
public:
    Lis1(string name) : Listener(name) {}
    void HandleMsg(int event)
    {
        cout << name_ << " ";
        switch (event)
        {
        case 1:
            cout << "do 1 event" << endl;
            break;
        case 2:
            cout << "do 2 event" << endl;
            break;
        }
    }
};

class Lis2 : public Listener
{
public:
    Lis2(string name) : Listener(name) {}
    void HandleMsg(int event)
    {
        cout << name_ << " ";
        switch (event)
        {
        case 2:
            cout << "do 2 event" << endl;
            break;
        case 3:
            cout << "do 3 event" << endl;
            break;
        }
    }
};

class Lis3 : public Listener
{
public:
    Lis3(string name) : Listener(name) {}
    void HandleMsg(int event)
    {
        cout << name_ << " ";
        switch (event)
        {
        case 1:
            cout << "do 1 event" << endl;
            break;
        case 3:
            cout << "do 3 event" << endl;
            break;
        }
    }
};

// 观察者
class Observer
{
public:
    //注册事件
    void AddEvent(Listener *lis, int event)
    {
        // 找到事件后,事件和监听者加入listenerMap_
        auto it = listenerMap_.find(event);  // O(1)
        if (it != listenerMap_.end())
        {
            it->second.emplace_back(lis);
        }
        else
        {
            vector<Listener*> vec{ lis };
            listenerMap_.emplace(event, vec);
        }

        // listenerMap_[event].emplace_back(lis);     // 技巧: 一句搞定
    }
    // 监听事件发生后,开始通知listener处理消息     通知(回调)
    void DispathEvent(int event)
    {
        // 找到event后  回调
        auto it = listenerMap_.find(event);
        if (it == listenerMap_.end())
        {
            return;
        }

        for (auto lis : it->second)
        {
            lis->HandleMsg(event);
        }
    }

private:
    // event  多个Listener监听者 Listener*
    unordered_map<int, vector<Listener*>> listenerMap_;
};
int main()
{
    Observer obser;
    Listener* l1 = new Lis1("a");
    Listener* l2 = new Lis2("a");
    Listener* l3 = new Lis3("a");

    obser.AddEvent(l1, 1);
    obser.AddEvent(l1, 2);
    obser.AddEvent(l2, 2);
    obser.AddEvent(l2, 3);
    obser.AddEvent(l3, 1);
    obser.AddEvent(l3, 3);

    for (;;)
    {
        cout << "输入事件:";
        int event;
        cin >> event;
        obser.DispathEvent(event);
    }

    return 0;
}

评论区

索引目录