Interview Question
Country: United States
The drawback of abstract factory design is that you have to have platfrom-specific code, e.g. as shown above:
if( Windows )
{
...
}
The same can be achieved by conditional compiling where the platform-specific implementation files are included. This way there is not need for special "WindowsFactory". Instead you can just use Factory class implemented for each platform in a separate .cpp file.
A simple example to explain:
- learner123 May 13, 2014class Widget
{
public:
virtual void Display() = 0;
};
class WindowsMenuItem : public Widget
{
public:
void Display()
{
cout << "Displaying Menu Item on Windows" << endl;
}
};
class WindowsEditBox : public Widget
{
public:
void Display()
{
cout << "Displaying Edit Box on Windows" << endl;
}
};
class MotifMenuItem : public Widget
{
public:
void Display()
{
cout << "Displaying Menu Item on Motif" << endl;
}
};
class MotifEditBox : public Widget
{
public:
void Display()
{
cout << "Displaying Edit Box on Motif" << endl;
}
};
class AbstractFactoryClass
{
public:
virtual Widget* CreateMenuItem() = 0;
virtual Widget* CreateEditBox() = 0;
};
class WindowsFactory : public AbstractFactoryClass
{
public:
Widget* CreateMenuItem()
{
return new WindowsMenuItem();
}
Widget* CreateEditBox()
{
return new WindowsEditBox();
}
};
class MotifFactory : public AbstractFactoryClass
{
public:
Widget* CreateMenuItem()
{
return new MotifMenuItem();
}
Widget* CreateEditBox()
{
return new MotifEditBox();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
AbstractFactoryClass* factory;
Widget *editBox, *menuItem;
if( Windows )
{
factory = new WindowsFactory();
editBox = factory->CreateEditBox();
menuItem = factory->CreateMenuItem();
}
else
{
factory = new MotifFactory();
editBox = factory->CreateEditBox();
menuItem = factory->CreateMenuItem();
}
editBox->Display();
menuItem->Display();
return 0;
}