本文主要是介绍Strategy模式实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
策略设计模式C++实现:
#include <iostream>
using namespace std;
#define GIF 1
#define JPEG 2
//Interface
class ImageSaver
{
public:virtual void save()=0;
};class GIFSaver:public ImageSaver
{
public:virtual void save(){cout<<"save GIF"<<endl;}
};class JPEGSaver:public ImageSaver
{
public:virtual void save(){cout<<"save GIF"<<endl;}
};class TypeChooser
{
public:static ImageSaver* getSaver(int type){if(type==GIF){return new GIFSaver();}else if(type==JPEG){return new JPEGSaver();}else{return NULL;}}
};int main()
{ImageSaver *saver=TypeChooser::getSaver(GIF);saver->save();saver=TypeChooser::getSaver(JPEG);saver->save();return 0;
}
这篇关于Strategy模式实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!