// 抽象策略
class IPolicy
{
public:
IPolicy() {}
virtual ~IPolicy() {}
public:
virtual int execute(int a, int b) = 0;
};
// 上下文
class context
{
public:
explicit context(IPolicy* policy):policy(policy) {}
~context() {
if (policy != NULL) {
delete policy;
}
}
public:
int exec(int a, int b) {
if (policy != NULL) {
return policy->execute(a, b);
}
return -1;
}
protected:
IPolicy* policy;
};
// 加法
class addPolicy: public IPolicy
{
public:
addPolicy() {}
~addPolicy() {}
public:
virtual int execute(int a, int b) {
return a + b;
}
};
// 减法
class subPolicy : public IPolicy
{
public:
subPolicy() {}
~subPolicy() {}
public:
virtual int execute(int a, int b) {
return a - b;
}
};
void test_policy{
context* ctx = NULL;
int a = 10;
int b = 5;
srand(time(NULL));
int mode = rand() % 10;
if (mode % 2) {
ctx = new context(new addPolicy());
}
else {
ctx = new context(new subPolicy());
}
if (ctx != NULL) {
int c = ctx->exec(a, b);
cout << "mode:" << mode << endl;
cout << c << endl;
}
delete ctx;
}