【C++ 策略设计模式 】

发布时间:2023年12月30日

策略设计模式
定义一组算法,将每个算法都封装起来,并且使它们之间可以互换

StartegyMode.cpp


#include <iostream>
 
using namespace std;
 
class IStrategy {
public:
	IStrategy() {}
	virtual ~IStrategy() {}
 
	virtual void Discountsfun() = 0;
};
 
class qxj : public IStrategy {
public:
	qxj() {}
	~qxj() {}
 
	void Discountsfun() {
		cout << "run qxj 20'%' off" << endl;
	}
};
 
class gqj : public IStrategy {
public:
	gqj() {}
	~gqj() {}
 
	void Discountsfun() {
		cout << "run gqj 10'%' off " << endl;
	}
};
 
class Context {
public:
	Context(IStrategy *IStrategy) { pIStrategy = IStrategy; }
	~Context() { delete pIStrategy; }
 
	void run() {
		pIStrategy->Discountsfun();
	}
 
private:
	IStrategy *pIStrategy;
};
 
 // g++ StartegyMode.cpp -o StartegyMode
int main(int argc, char*argv[])
{
	Context context1(new qxj());
	context1.run();
 
	Context context2(new gqj());
	context2.run();
 
	return 0;
}

文章来源:https://blog.csdn.net/weixin_45397344/article/details/135278308
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。