Answer to Question #261331 in C++ for Appu

Question #261331

 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


1
Expert's answer
2021-11-05T17:26:17-0400


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

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS