Created
October 4, 2014 21:15
-
-
Save kazmura11/67738baa2d0104760195 to your computer and use it in GitHub Desktop.
Design Pattern Abstract Factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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