常用的设计模式

面向对象设计原则

1.单一职责原则(SRP):一个类只应该有一个职责,即只负责一块功能或领域。

2.开闭原则(OCP):对于扩展开放,对于修改关闭。即,已有的代码应该尽量不需要修改,在增加新功能时尽量使用扩展的方式。

3.里氏替换原则(LSP):子类可以替换父类,并保证原有的代码不受影响。

4.依赖倒置原则(DIP):高层模块不应该依赖于底层模块。应该通过抽象接口来解耦合。

5.接口隔离原则(ISP):不应该强制依赖与自己不需要的接口。应该根据需求,将接口分离成更小、更专门化的部分。

6.迪米特原则(LoD):又称最少知道原则,即一个模块或对象应该尽可能少的了解其它模块或者对象的信息。

7.合成复用原则(CRP):尽量组合,少使用继承。即尽量不使用继承的方式实现代码复用,而是使用组合和聚合等方式。

设计模式

工厂方法

定义:

工厂方法模式:定义一个用于创建对象的接口,让子类决定将哪一个类实例化

示例:

#include<iostream>
using namespace std;

class Fruit
{
public:
    virtual void showname()=0;
    virtual ~Fruit(){};
};

class Apple:public Fruit{
    public:
    void showname(){
        cout<<"Apple"<<endl;
    }
};

class Banana:public Fruit
{
public:
       
   void showname(){
    cout<<"Banana"<<endl;
   }
private:
    int a;
};


class Factory
{
public:
    virtual Fruit* createFruit() = 0;
    virtual ~Factory(){};
};

class FactoryApple:public Factory
{
public:
    Fruit* createFruit()
    {
        return new Apple();
    }
};

class FactoryBanana:public Factory
{
public:
    virtual Fruit* createFruit()
    {
        return new Banana();
    }

};
int main()
{
    int a=10;
    Factory *factory = new FactoryApple();
    Fruit *fruit = factory->createFruit();
    fruit->showname(); 
    return 0;
}

抽象工厂模式

定义:

抽象工厂是一种对象创建模式,它提供了一个创建一系列相关对象的接口,而不需要指定具体的类。工厂方法模式只有一个抽象产品,而抽象工厂模式有多个

示例:

#include<iostream>
using namespace std;

class player
{
public:
    virtual void attack() = 0;
    virtual void character_information() = 0;
};
class Garen:public player
{
public:
    Garen(int _HP,int _ATK,int _DEF):HP(_HP),ATK(_ATK),DEF(_DEF){}
    void attack()
    {
        cout<<"使用宝剑攻击敌人"<<endl;
    }
    void character_information()
    {
        cout <<"生命值:"<<HP<<endl;
        cout <<"攻击力:"<<ATK<<endl;
        cout <<"防御力:"<<DEF<<endl;
    }
public:
    int HP;
    int ATK;
    int DEF;
};

class Ryze:public player
{
public:
    Ryze(int _HP,int _ATK,int _DEF):HP(_HP),ATK(_ATK),DEF(_DEF){}
    void attack()
    {
        cout<<"使用法术攻击敌人"<<endl;
    }
    void character_information()
    {
        cout <<"生命值:"<<HP<<endl;
        cout <<"攻击力:"<<ATK<<endl;
        cout <<"防御力:"<<DEF<<endl;
    }
public:
    int HP;
    int ATK;
    int DEF;
};

class creeps
{
    public:
    virtual void attack() = 0;
    virtual void information() = 0;
};
class blue_buff:public creeps
{
public:
    blue_buff(int _HP,int _ATK,int _DEF):HP(_HP),ATK(_ATK),DEF(_DEF){}
    void attack()
    {
        cout<<"攻击玩家"<<endl;
    }
    void information()
    {
        cout <<"生命值:"<<HP<<endl;
        cout <<"攻击力:"<<ATK<<endl;
        cout <<"防御力:"<<DEF<<endl;
    }
public:
    int HP;
    int ATK;
    int DEF;
};
class Dragon:public creeps
{
public:
    Dragon(int _HP,int _ATK,int _DEF):HP(_HP),ATK(_ATK),DEF(_DEF){}
    void attack()
    {
        cout<<"吐火焰攻击玩家"<<endl;
    }
    void information()
    {
        cout <<"生命值:"<<HP<<endl;
        cout <<"攻击力:"<<ATK<<endl;
        cout <<"防御力:"<<DEF<<endl;
    }
public:
    int HP;
    int ATK;
    int DEF;
};

class GameFactory
{
public:
    virtual  player* create_player() = 0;
    virtual  creeps* create_creeps() = 0;
};

class GameFactory1 : public GameFactory
{
public:
    virtual  player* create_player()
    {
        return new Ryze(100,15,2);
    }
    virtual creeps* create_creeps()
    {
        return new blue_buff(30,2,1);
    }
};

class GameFactory2 : public GameFactory
{
public:
    virtual  player* create_player()
    {
        return new Garen(150,30,15);
    }
    virtual creeps* create_creeps()
    {
        return new Dragon(230,15,50);
    }
};

int main()
{
    GameFactory *factory = new GameFactory1();
    creeps* creeps1 = factory->create_creeps();
    player* player1 = factory->create_player();

    player1->character_information();
    player1->attack();

    creeps1->attack();
    creeps1->information();

}

单例模式

定义:

保证一个类仅有一个实例,并提供一个访问它的全局访问点

示例:

#include<iostream>
using namespace std;

/*  1.构造函数私有化
    2.增加一个静态的并且私有的当前类的指针变量
    3.提供静态对外接口,可以让用户获得单例对象
*/

//懒汉式  第一次用到类实例的时候才会去实例化
class SingletonLazy
{
private:
    SingletonLazy(){}
public:
    static SingletonLazy* getInstance(){
        if(instance=nullptr)
        {
            instance = new SingletonLazy();
            return instance;
        }

    }
private:
    static SingletonLazy* instance;
};
SingletonLazy* SingletonLazy::instance=nullptr;

//饿汉式  单例类定义的时候就进行了实例化
class SingletonHungry
{
private:
    SingletonHungry(){}
public:
    static SingletonHungry* getInstance(){
        return instance;
    }
private:
    static SingletonHungry* instance;
};
SingletonHungry* SingletonHungry::instance= new SingletonHungry();

模板方法

定义:

模板方法模式:定义一个操作中算法的框架,而将一些步骤延迟到子类中,模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些步骤。

示例:

#include<iostream>

using namespace std;

class Drink{
public:
    virtual void BoilWrite() = 0;
    virtual void Brew() = 0;
    virtual void AddSomething() = 0;

    void  run()
    {
        BoilWrite();
        Brew();
        AddSomething();
    }
    virtual ~Drink(){}
};

class Tea:public Drink
{
public:
    virtual void BoilWrite()
    {
        cout<<"煮自来水"<<endl;
    }
    virtual void Brew()
    {
        cout <<"冲泡茶叶"<<endl;
    }
    virtual void AddSomething()
    {
        cout<<"加入糖"<<endl;
    }
};

class Coffee:public Drink
{
public:
    virtual void BoilWrite()
    {
        cout<<"煮山泉水"<<endl;
    }
    virtual void Brew()
    {
        cout <<"冲泡咖啡"<<endl;
    }
    virtual void AddSomething()
    {
        cout<<"加入牛奶"<<endl;
    }
};
int main()
{
     Tea T;
     T.run();
     Coffee C;
     C.run();
}

策略模式

定义:

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

示例:

#include<iostream>
using namespace std;

class travel_strategy{
    public:
     virtual void choose_method() = 0;
     virtual ~travel_strategy(){};
};

class strategy_a:public travel_strategy
{
public:
    virtual void choose_method()
    {
        cout<<"坐飞机"<<endl;
    }
};

class strategy_b:public travel_strategy
{
public:
    virtual void choose_method()
    {
        cout<<"坐火车"<<endl;
    }
};

class stratgy_table{
public:
    stratgy_table(travel_strategy* p): ps_table(p){};
    void get_method(){
        ps_table->choose_method();
    };
private:
    travel_strategy* ps_table;    
};

int main()
{
    stratgy_table* pstratgy_tablea = new stratgy_table(new strategy_a());
    stratgy_table* pstratgy_tableb = new stratgy_table(new strategy_b());
    pstratgy_tablea->get_method();
    pstratgy_tableb->get_method();

}

代理模式

定义:

代理模式是构造型的设计模式之一,它可以为其他对象提供一种代理以控制对这个对象的访问。 所谓代理,是指具有与代理元(被代理的对象)具有相同的接口的类,客户端必须 通过代理与被代理的目标类交互,而代理一般在交互的过程中(交互前后),进行某些 特别的处理。

示例:

#include<iostream>
using namespace std;

class Ticket
{
public:
    virtual void buy_ticket() =0;
};

class people:public Ticket 
{
public:
    virtual void buy_ticket()
    {
        cout<<"买票"<<endl;
    }
};

class APP_proxy:public Ticket
{
public:
    APP_proxy(Ticket* p):ticket(p){}
    virtual void buy_ticket()
    {
        cout<<"验证身份"<<endl;
        ticket->buy_ticket();
    }
    ~APP_proxy(){
        delete ticket;
    }
private:
    Ticket* ticket;
};

int main()
{
    Ticket *ren = new people();
    APP_proxy  P(ren);
    P.buy_ticket();
}

适配器

定义:

适配器模式是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。

示例:

#include<iostream>
using namespace std;

class US_computr{
public:
    void load_ui()
    {
        cout<<"加载界面"<<endl;
    }
int V = 120;
};
class China
{
public:
    China(int _V):V(_V){}
    void use_computr()
    {
        if(V==200)
        {
            cout<<"开启成功"<<endl;
        }
        else
        cout<<"开启失败"<<endl;
    }
private:
    int V;
};

class Adapter:public US_computr
{
public:
    Adapter(US_computr* us):US(us){}
    
    void change()
    {
        US->V = this->V;
    }
private:
int V=200;
US_computr* US;
};
int main()
{
    US_computr* US = new US_computr();
    Adapter ad(US);
    ad.change();
    China ch(US->V);
    ch.use_computr();
    US->load_ui();
}

桥接模式

定义:

将抽象部分与它的实现部分分离,使它们都可以独立地变化。

示例:

#include<iostream>
using namespace std;

class OS
{
public:
    virtual void installOS_Imp() =0;
};

class Linux:public OS
{
    public:
        void installOS_Imp(){
            cout<<"安装Linux系统"<<endl;
        }
};

class Window:public OS
{
    public:
        void installOS_Imp(){
            cout<<"安装Window系统"<<endl;
        }
};

class Computer
{
    public:
        virtual void installOS(OS *os) =0;
};

class AppleComputer:public Computer
{
    public:
        void installOS(OS *os)
        {
            os->installOS_Imp();
        }
};
class HuaWeiComputer:public Computer
{
    public:
        void installOS(OS *os)
        {
            os->installOS_Imp();
        }

};

int main()
{
    OS *os1 = new Linux();
    OS *os2 = new Window();

    Computer *computer = new AppleComputer();
    computer->installOS(os1);
    computer->installOS(os2);
    delete os1;
    delete os2;
    os1=nullptr;
    os2=nullptr;
}

备忘录模式

定义:

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态

示例:

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

class Memento
{
public:
    Memento(int m_blood,int m_defense,int m_attack):blood(m_blood),defense(m_defense),attack(m_attack){}
public:
    int blood;
    int defense;
    int attack;
};
class GameRole
{
public:
    GameRole():blood(100),defense(20),attack(10){}
    Memento Save()
    {
        Memento memento(blood,defense,attack);
        return memento;
    }
    void Load(Memento memento)
    {
        blood = memento.blood;
        attack = memento.attack;
        defense = memento.defense;
    }
    void show()
    {
        cout<<"血量:"<<blood<<endl;
        cout<<"防御:"<<defense<<endl;
        cout<<"攻击力:"<<attack<<endl;
    }
    void update()
    {
        this->blood =this->blood +10;
        this->attack = this->attack+5;
        this->defense = this->defense+3;
    }
private:
    int blood;
    int defense;
    int attack;
};

class GameSave
{
public:
    void Save(Memento memento)
    {
        v.push_back(memento);
    }
    Memento Load(int state)
    {
        return v.at(state);
    }

private:
    vector<Memento> v;
};

int main()
{
    GameRole role;
    GameSave gamesave;
    cout<<"角色初始状态"<<endl;
    role.show();
    gamesave.Save(role.Save());
    cout<<"升级后状态"<<endl;
    role.update();
    role.update();
    role.show();
    gamesave.Save(role.Save());
    cout<<"回到初始状态"<<endl;
    role.Load(gamesave.Load(0));
    role.show();

}

观察者模式

定义:

对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

示例:

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


class Observer
{
public:
    virtual void Updata(char *message,int count) = 0;

};

class peopleA : public Observer
{
public:
    void Updata(char *message,int count)
    {
        cout<<"当前订阅人数:"<<count<<endl;
        cout<<"PeopleA:"<<message<<endl;
    }
};
class peopleB : public Observer
{
public:
    void Updata(char* message,int count)
    {
        cout<<"当前订阅人数:"<<count<<endl;
        cout<<"PeopleB:"<<message<<endl;
    }
};

class Subject
{
public:
    virtual void Attach(Observer *observer) = 0;     //添加订阅者
    virtual void Detach(Observer *observer) = 0;     //删除订阅者
    virtual void Notify() = 0;         //通知
protected:
    list<Observer *>  m_observer;     //存储订阅者
};

class Message : public Subject
{   
public:
    void  UpdataMessage(char* message)
    {
        this->m_message = message;
    }
    void Attach(Observer *observer)
    {
        m_observer.push_back(observer);
        count++;
    }
    void Detach(Observer *observer)
    {
        m_observer.remove(observer);
    }
    void Notify()
    {
        list<Observer *>::iterator it = m_observer.begin();
        while (it != m_observer.end())
        {
            (*it)->Updata(m_message,count);
            it++;
        }
        
    }
private:
    char* m_message;
    int count=0;
};

int main()
{
    Message* message = new Message();

    Observer* A = new peopleA();
    Observer* B = new peopleB();

    message->Attach(A);
    message->Attach(B);

    message->UpdataMessage("hello");
    message->Notify();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值