设计模式之策略模式(Strategy)

来源:互联网 发布:mysql 数据库重命名 编辑:程序博客网 时间:2024/06/08 13:21

策略模式是指定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。使得算法可独立于使用它的客户而变化。也就是说这些算法所完成的功能一样,对外的接口一样,只是各自实现上存在差异。用策略模式来封装算法,效果比较好

#include <iostream>using namespace std;//抽象接口class Algorithm{public:    virtual void replace() = 0;};//算法1class Algorithm1 : public Algorithm{public:    void replace()    {        cout << "this is Algorithm1" << endl;    }};//算法2class Algorithm2 : public Algorithm{public:    void replace()    {        cout << "this is Algorithm2" << endl;    }};//算法3class Algorithm3 : public Algorithm{public:    void replace()    {        cout << "this is Algorithm3" << endl;    }};enum AlgorithmFlag{    A1,    A2,    A3};//计算class Compute{public:    Compute(enum AlgorithmFlag flag)    {        if(flag == A1)            _algorithm = new Algorithm1;        else if(flag == A2)            _algorithm = new Algorithm2;        else if(flag == A3)            _algorithm = new Algorithm3;        else            _algorithm = NULL;    }    ~Compute()    {        if(_algorithm)            delete _algorithm;    }    void replace()    {        _algorithm->replace();    }private:    Algorithm *_algorithm;};int main(){    Compute compute(A1);    compute.replace();    return 0;}

这里写图片描述

原创粉丝点击