FactoryMethod - shoonie/StudyingDesignPattern GitHub Wiki

Intent

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclass.

Diagram

disgram

Consequences

  1. Provides hooks for subclasses.
  2. Connects parallel class hierarchies.
  3. It gives you finer control over the construction process.

Implementation

  1. Two major varieties.
  1. The case when the Creator class is abstract class and does not provide an implementation for the factory method it declares.
  2. The case when the Creator is a concrete class and provides a default implementation for the factory method.
  1. Parameterized factory methods
  2. Language-specific variants and issues.

Sample Code

  1. 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;
}
  1. 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;
}
⚠️ **GitHub.com Fallback** ⚠️