Skip to content

Instantly share code, notes, and snippets.

@kazmura11
Created October 4, 2014 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazmura11/67738baa2d0104760195 to your computer and use it in GitHub Desktop.
Save kazmura11/67738baa2d0104760195 to your computer and use it in GitHub Desktop.
Design Pattern Abstract Factory
#include <iostream>
class Button {
public:
virtual void paint() = 0;
virtual ~Button() { }
};
class WinButton : public Button {
public:
void paint() override {
std::cout << "I'm a WinButton";
}
~WinButton() { }
};
class OSXButton : public Button {
public:
void paint() override {
std::cout << "I'm an OSXButton";
}
~OSXButton() { }
};
class GUIFactory {
public:
virtual Button *createButton() = 0;
virtual ~GUIFactory() { }
};
class WinFactory : public GUIFactory {
public:
Button *createButton() override {
return new WinButton();
}
~WinFactory() { }
};
class OSXFactory : public GUIFactory {
public:
Button *createButton() override {
return new OSXButton();
}
~OSXFactory() { }
};
class Application {
public:
Application(GUIFactory *factory) {
if (factory != NULL)
{
Button *button = factory->createButton();
button->paint();
delete button;
delete factory;
}
else
{
std::cerr << "Fatal Error!!" << std::endl;
}
}
};
GUIFactory *createOsSpecificFactory() {
int sys;
std::cout << "Enter OS type (0: Windows, 1: MacOS X): ";
std::cin >> sys;
switch (sys)
{
case 0:
return new WinFactory();
case 1:
return new OSXFactory();
default:
std::cerr << "The number you chose is out of range!!" << std::endl;
return nullptr;
}
}
int main() {
Application application(createOsSpecificFactory());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment