Problem
A utility class that creates an instance of a class from a family of derived classes
Solution
#include <iostream>
using namespace std;
class os
{
public:
os(){};
~os(){};
};
class linux:os
{
public:
linux(){cout << "Linux"; };
virtual ~linux(){};
};
class windows:os
{
public:
windows(){cout << "windows"; };
virtual ~windows(){};
};
class os_factory
{
private:
public:
enum os_type{LINUX, WINDOWS};
static os* create_os(os_type type)
{
if(type == os_type::LINUX)
{
return (os *)new linux;
}
else{
return (os *)new windows;
}
return NULL;
}
};
int main(int argc, char* argv[])
{
os *os1 = os_factory::create_os(os_factory::LINUX);
return 0;
}
Output
linux