Rewrite the code in C++ using Factory Method. The goal is to remove the
main function’s dependency on the concrete classes, such as GoToSchool.
#ifndef GOTOSCHOOL_H
#define GOTOSCHOOL_H
#include <iostream>
using namespace std;
class GoToSchool {
void getUp() { cout << "Get up." << endl; }
void eatBreakfest() { cout << "Eat breakfest." << endl; }
virtual void takeTransit() { cout << "Take school bus." << endl; }
virtual void arrive() = 0;
public:
void go() {
getUp();
eatBreakfest();
takeTransit();
arrive();
}
};
#endif
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
#include <iostream>
#ifndef GOTOSCHOOL_H
#define GOTOSCHOOL_H
#include <memory>
#include <string>
using namespace std;
//define a baseclass
class MyBaseClass
{
public:
virtual void doSomething() = 0;
};
//create a factory class
class MyFactory
{
public:
static shared_ptr<MyBaseClass> CreateInstance(string name);
};
//define our class Gotoschool as a derived class
class GoToSchool : public MyBaseClass
{
public:
GoToSchool(){};
virtual ~GoToSchool(){};
void getUp() { cout << "Get up." << endl; }
void eatBreakfest() { cout << "Eat breakfest." << endl; }
virtual void takeTransit() { cout << "Take school bus." << endl; }
virtual void arrive() = 0;
public:
void go() {
getUp();
eatBreakfest();
takeTransit();
arrive();
}
};
//Implement a factory method
// this factory methods receives a string
shared_ptr<MyBaseClass> MyFactory::CreateInstance(string name)
{
MyBaseClass * instance = nullptr;
if(name == "one")
instance = new GoToSchool();
if(instance != nullptr)
return std::shared_ptr<MyBaseClass>(instance);
else
return nullptr;
}
//main method
int main(int argc, char** argv)
{
auto instanceOne = MyFactory::CreateInstance("one");
// call the go method in GOToschool function
instanceOne->go();
return 0;
}
#endif
Comments
Leave a comment