您的位置:首页 > 编程语言 > C语言/C++

C++设计模式学习之策略模式

2017-08-10 21:12 232 查看
Strategy:行为模式

封装算法:为所有的算法提供一个抽象的算法接口,并通过继承该抽象接口对所有的算法加以封装和实现。

具体的算法选择交由客户端决定。把公共代码提取公因式到父类
#include<stdlib.h>
#include<iostream>
using namespace std;
class Strategy{
public:
virtual void SymEncrypt() = 0;
};

class Des :public Strategy{
public:
virtual void SymEncrypt(){
cout << "使用DES加密" << endl;
}
};

class AES :public Strategy{
public:
virtual void SymEncrypt(){
cout << "AES加密" << endl;
}
};

class Context{
public:
Context(Strategy *s){
p = s;
}
void Operate(){
p->SymEncrypt();
}
protected:
private:
Strategy *p;
};
void main(){
//Strategy *s = NULL;
//s = new AES;
//s->SymEncrypt();
//delete s;

Strategy *s = NULL;
Context *ctx = NULL;
s = new AES;
ctx = new Context(s);
ctx->Operate();
delete s;
delete ctx;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: