FactoryMethod - shoonie/StudyingDesignPattern GitHub Wiki
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclass.
- Provides hooks for subclasses.
- Connects parallel class hierarchies.
- It gives you finer control over the construction process.
- Two major varieties.
- The case when the Creator class is abstract class and does not provide an implementation for the factory method it declares.
- The case when the Creator is a concrete class and provides a default implementation for the factory method.
- Parameterized factory methods
- Language-specific variants and issues.
- Factory Method - Abstract Creator Class
#include <iostream>
class Button {
public:
virtual void paint() = 0;
};
class OSXButton: public Button {
public:
void paint() {
std::cout << "OSX button \n";
}
};
class WindowsButton: public Button {
public:
void paint() {
std::cout << "Windows button \n";
}
};
class GUIFactory {
public:
virtual Button *createButton(char *) = 0;
};
class Factory: public GUIFactory {
public:
Button *createButton(char *type) {
if(strcmp(type,"Windows") == 0) {
return new WindowsButton;
}
else if(strcmp(type,"OSX") == 0) {
return new OSXButton;
}
}
};
int main()
{
GUIFactory* guiFactory;
Button *btn;
guiFactory = new Factory;
btn = guiFactory->createButton("OSX");
btn -> paint();
btn = guiFactory->createButton("Windows");
btn -> paint();
return 0;
}
- Factory Method - Concrete Creator Class
#include <iostream>
class Button {
public:
virtual void paint() = 0;
};
class OSXButton: public Button {
public:
void paint() {
std::cout << "OSX button \n";
}
};
class WindowsButton: public Button {
public:
void paint() {
std::cout << "Windows button \n";
}
};
class iPhoneButton: public Button {
public:
void paint() {
std::cout << "iPhone button \n";
}
};
class GUIFactory {
public:
virtual Button *createButton(char *type) {
if(strcmp(type,"Windows") == 0) {
return new WindowsButton;
}
else if(strcmp(type,"OSX") == 0) {
return new OSXButton;
}
return NULL;
}
};
class Factory: public GUIFactory {
Button *createButton(char *type) {
if(strcmp(type,"Windows") == 0) {
return new WindowsButton;
}
else if(strcmp(type,"OSX") == 0) {
return new OSXButton;
}
else if(strcmp(type,"iPhone") == 0) {
return new iPhoneButton;
}
}
};
int main()
{
GUIFactory* guiFactory;
Button *btn;
guiFactory = new Factory;
btn = guiFactory->createButton("OSX");
btn -> paint();
btn = guiFactory->createButton("Windows");
btn -> paint();
btn = guiFactory->createButton("iPhone");
btn -> paint();
return 0;
}