Created
October 4, 2014 21:04
-
-
Save kazmura11/ba408a315705845fb8df to your computer and use it in GitHub Desktop.
Design Pattern 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 Computer | |
{ | |
public: | |
virtual ~Computer() {} | |
virtual void run() = 0; | |
virtual void stop() = 0; | |
}; | |
class Laptop : public Computer | |
{ | |
public: | |
virtual ~Laptop() {} | |
virtual void run() override | |
{ | |
hibernating_ = false; | |
std::cout << "ハイバーネート解除します(*´Д`)" << std::endl; | |
} | |
virtual void stop() override | |
{ | |
hibernating_ = true; | |
std::cout << "ハイバーネートします(´・ω・`)" << std::endl; | |
} | |
private: | |
bool hibernating_; // ハイバーネート中かどうか | |
}; | |
class Desktop : public Computer | |
{ | |
public: | |
virtual ~Desktop() {} | |
virtual void run() override | |
{ | |
on_ = true; | |
std::cout << "起動しますた(*´ω`*)" << std::endl; | |
} | |
virtual void stop() override | |
{ | |
on_ = false; | |
std::cout << "電源切ります(;´Д`)" << std::endl; | |
} | |
private: | |
bool on_; // 起動中かどうか | |
}; | |
class ComputerFactory | |
{ | |
public: | |
enum ComputerType { | |
LaptopType, | |
DesktopType | |
}; | |
static Computer* create(ComputerType description) | |
{ | |
switch (description) | |
{ | |
case LaptopType: | |
return new Laptop(); | |
case DesktopType: | |
return new Desktop(); | |
default: | |
return nullptr; | |
} | |
} | |
}; | |
int main() | |
{ | |
Computer *laptop = ComputerFactory::create(ComputerFactory::LaptopType); | |
laptop->run(); | |
laptop->stop(); | |
Computer *desktop = ComputerFactory::create(ComputerFactory::DesktopType); | |
desktop->run(); | |
desktop->stop(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment