Skip to content

Instantly share code, notes, and snippets.

@kazmura11
Created October 4, 2014 21:04
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/ba408a315705845fb8df to your computer and use it in GitHub Desktop.
Save kazmura11/ba408a315705845fb8df to your computer and use it in GitHub Desktop.
Design Pattern Factory
#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