当遇到同一个对象有不同的行为,方法,为管理这些方法可使用策略模式。
策略模式就是对算法进行包装,是把使用算法的责任和算法本身分割开来。通常把一个系列的算法包装到一系列的策略类里面,这些类继承一个抽象的策略类。使用这些算法的时候,只需要调用子类即可。
例如:
class LearnTool
{
public:
void virtual useTool() = ;
}; class BookTool:public LearnTool
{
public:
void useTool()
{
cout << "Learn by book !" << endl;
}
}; class ComputerTool:public LearnTool
{
public:
void useTool()
{
cout << "Learn by computer !" << endl;
}
}; class Person
{
public:
Person()
{
tool = ;
}
void setTool(LearnTool *w)
{
this->tool = w;
}
void virtual Learn() = ;
protected:
LearnTool *tool;
}; class Tom:public Person
{
public:
void Learn()
{
cout << "The Tom:" ;
if ( this->tool == NULL)
{
cout << "You have`t tool to learn !" << endl;
}
else
{
tool->useTool();
}
}
};
int main()
{
LearnTool *book = new BookTool();
LearnTool *computer = new ComputerTool(); Person *tom = new Tom(); tom->Learn();
cout << endl; tom->setTool(book);
tom->Learn();
cout << endl; tom->setTool(computer);
tom->Learn(); return ;
}