Strategy-Rule Mode
DefinitionDefine a series of algorithms, encapsulate them one by one, and make them replace each other. The policy pattern allows algorithms to change independently of users.
CaseFor example, a file Editor can be saved in any format when it is saved. All file content conversion is provided by Convertor, and different content conversion support is provided based on different options: TXTConvertor, PDFConvertor, DOCConvertor, and so on. Editor maintains a reference to the Convertor object. Once you want to convert the file content, it will hand over its responsibilities to the Convertor object. Separating the conversion algorithm from the Editor can simplify the Code complexity, facilitate maintenance, and effectively expand new algorithms. You do not have to use a public base class when implementing it. You can also use the template method. Here the base class method is used:
Maintain a Convertor object in the Editor class and call the related methods of this object when saving:
class Editor
{
public:
void save();
void setConvertor(Convertor* convertor) { m_convertor = convertor; }
private:
string m_text;
Convertor* m_convertor;
};
void Editor::save()
{
String text = m_convertor->convert(m_text);
// save text to file.
}
Convertor provides interfaces for the Editor to call:
class Convertor
{
public:
vritual string& convert(const string& text) = 0;
};
Its subclass implements the method differently:
class TXTConvertor : public Convertor
{
public:
virtual string& convert(const string& text)
{
// convert to txt data.
}
};
class PDFConvertor : public Convertor
{
public:
virtual string& convert(const string& text)
{
// convert to pdf data.
}
};
class DOCConvertor : public Convertor
{
public:
virtual string& convert(const string& text)
{
// convert to doc data.
}
};
In use, set different Convertor according to different situations:
Edtior* editor = new Editor();
Convertor* txtConvertor = new TXTConvertor();
editor->setConvertor(txtConvertor);
editor->save();
...
Convertor* pdfConvertor = new PDFConvertor();
editor->setConvertor(pdfConvertor);
editor->save();
ApplicabilityIf many classes only have different behaviors, you need to use different variants of an algorithm to use data that you do not know, policy mode avoids exposing complex algorithm-related data structures. A class defines multiple behaviors, and these behaviors appear in this class in the form of multiple conditional statements.