策略模式
#include <iostream>
#include <string>
using namespace std;
class fruit {
public:
virtual string getCorlor() = 0;
};
class apple :public fruit {
public:
virtual string getCorlor() {
return "红色";
}
};
class pear :public fruit {
public:
virtual string getCorlor() {
return "黄色";
}
};
class orange :public fruit {
public:
virtual string getCorlor() {
return "橙色";
}
};
enum FRUIT
{
APPLE = 1,
PEAR,
ORANGE
};
class Context {
private:
fruit* m_fruit;
public:
Context(FRUIT f){
switch (f)
{
case APPLE:
m_fruit = new apple();
break;
case PEAR:
m_fruit = new pear();
break;
case ORANGE:
m_fruit = new orange();
break;
default:
break;
}
}
string getarithmetic() {
return m_fruit->getCorlor();
}
};
int main() {
/*
简单工厂+策略模式
好处是客户端只需要关心Context类即可
*/
Context* c = new Context(APPLE);
cout << c->getarithmetic() << endl;
return 0;
}