Factory methods
Factory functions or factory method pattern is an object oriented design pattern to implement the concept of factories. The idea behind factory method is to enable creation of objects without knowing the exact class that will be created. This simplifies the idea of abstraction, prevents duplicate code, prevent unnecessary include and allowing the composing class not to concern regarding the created class.
Let’s take for example a conversion program. Our program receives a number as input, the type of conversion need to be done and will output the result of the conversion. One way doing this is writing a conversion method with a long switch-case which will probably look like this:
float Convert(float _input, int _type)
{
Float res = 0;
Switch (_type)
{
Case 1:
…
Break;
Case 2:
…
Break;
…
…
}
Return res;
}
This will work fine, but every new conversion type must be added to this conversion function. Now let’s make things a bit more complicated, let’s assume that we need to perform input and output validation, which is different for every converter. It’s bit more complicated but still easy using object-oriented classes. The new code should look something like this:
BaseCoverter *CreateConverter(int _type)
{
Switch (_type)
{
Case 1: return new …
Case 2: return new …
…
…
}
Return new BaseConverter();
}
float Convert(float _input, int _type)
{
BaseCoverter *pConverter = CreateConverter(_type);
If (pConverter->isValidInput(_input) != true)
Return 0;
Float res = pConverter->convert(_input);
If (pConverter->isValidOutput(res) != true)
Return 0;
delete pConverter;
Return res;
}
Now we still have the same long switch-case function, just this time it moved to the converter creation function. This is where factory method comes in handy, if we could have just get rid of this long switch-case function can create the converters dynamically then it would have been much easier.
Here is an example of a simple factory class (.h):
#include