27.1 策略模式 VS 命令模式
27.1.1 策略模式实现压缩算法
//行为型模式大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压缩成功 */