27.1 策略模式 VS 命令模式

27.1.1 策略模式实现压缩算法

第28章 行为型模式大PK

//行为型模式大PK——策略模式和命令模式
//实例:用策略模式实现压缩算法
#include <iostream>
#include <string>

using namespace std;

//抽象压缩算法
class Algorithm
{
public:
    //压缩算法
    virtual bool compress(string source, string to) = 0;
    //解压算法
    virtual bool uncompress(string source, string to) = 0;

    virtual ~Algorithm(){}
};

//具体算法:zip算法
class Zip : public Algorithm
{
public:
    //zip格式的压缩算法
    bool compress(string source, string to)
    {
        cout << source << " --> " << to <<" ZIP压缩成功" <<endl;
        return true;
    }
    //zip格式的解压缩算法
    bool uncompress(string source, string to)
    {
        cout << source <<" --> " << to <<" ZIP解压缩成功" <<endl;
        return true;
    }
};

//具体算法:Gzip
class Gzip : public Algorithm
{
public:
    //gzip格式的压缩算法
    bool compress(string source, string to)
    {
        cout << source << " --> " << to <<" GZIP压缩成功" <<endl;
        return true;
    }
    //gzip格式的解压缩算法
    bool uncompress(string source, string to)
    {
        cout << source <<" --> " << to <<" GZIP解压缩成功" <<endl;
        return true;
    }
};

//环境角色
class Context
{
private:
    Algorithm* al; //指向抽象算法
public:
    Context(Algorithm* al)
    {
        this->al = al;
    }

    //设置算法策略
    void setAlgorithm(Algorithm* al)
    {
        this->al = al;
    }

    //执行压缩算法
    bool compress(string source, string to)
    {
        return al->compress(source ,to);
    }

    //执行解压缩算法
    bool uncompress(string source, string to)
    {
        return al->uncompress(source ,to);
    }
};

int main()
{
    //创建两种算法策略
    Algorithm* alZip = new Zip();
    Algorithm* alGzip = new Gzip();

    //创建环境角色,并执行zip算法
    Context ctx(alZip);

    cout <<"========执算zip算法========" << endl;
    //执行压缩算法
    ctx.compress("c:\\window", "d:\\windows.zip");
    //执行解压缩算法
    ctx.compress("c:\\window.zip", "d:\\windows");

    //"========执算gzip算法========"
    cout <<"========执算gzip算法========" << endl;
    //更换算法
    ctx.setAlgorithm(alGzip);

    //执行压缩算法
    ctx.compress("c:\\window", "d:\\windows.zip");
    //执行解压缩算法
    ctx.compress("c:\\window.zip", "d:\\windows");

    delete alZip;
    delete alGzip;
    return 0;
};
/*输出结果:
========执算zip算法========
c:\window --> d:\windows.zip ZIP压缩成功
c:\window.zip --> d:\windows ZIP压缩成功
========执算gzip算法========
c:\window --> d:\windows.zip GZIP压缩成功
c:\window.zip --> d:\windows GZIP压缩成功
*/
View Code

相关文章:

  • 2021-06-12
  • 2021-10-27
  • 2021-07-20
  • 2021-11-20
  • 2021-06-20
  • 2021-12-30
猜你喜欢
  • 2021-09-22
  • 2021-08-05
  • 2021-11-19
  • 2021-07-11
  • 2022-01-12
  • 2021-09-30
相关资源
相似解决方案