mercredi 25 janvier 2017

C++ How to turn a factory pattern into a Policy-based design

I am programming in C++ & new to the design concepts. I've been reading a lot of around how compile time type deduction can improve performance at run time. Also trying get a hold of templates programming which is a difficult part of C++ as I see.

I have the following code which is a Factory pattern.

/*The abstract class*/
Class Vehicle {
  virtual void Drive() = 0;
  virtual void Break() = 0;
  virtual void StartEngine() {
    //some default logic;
  }

  static std::unique_ptr<Vehicle> Factory(enum which_vehicle) {
    switch (which_vehicle) {
    case car:
      std::make_unique<Car>(which_vehicle);
      break;
    case bus:
      std::make_unique<Bus>(which_vehicle);
      break;
    }
  }
}

    --Car.hpp--
/*The derived class Car*/
Class Car : public Vehicle {
  void Drive(){
    //drive car;
  }
  void Brake(){
    //apply car brakes;
  }
  void StartEngine() {
    //Start car engine;
  }
}

    --Bus.hpp--
/*The derived class Bus*/
Class Bus : public Vehicle {
  void Drive(){
    //drive bus;
  }
  void Brake(){
    //apply bus brakes;
  }
  void StartEngine() {
    //Start bus engine;
  }
}

#include "Vehicle.hpp"
main() {
  //Get the required object
  std::unique_ptr<Vehicle> vehicle = Vehicle::Factory(enum::car);
}

As you can see in main method, enum type sent into Vehicle::Factory determines which object I create. Can I achieve the same design with templates based? Or can I make it a policy based design ?

I looked at some related discussions like here & here which looks pretty old style code. hence did not help. I need the exact code since I am new to C++ templates.

Aucun commentaire:

Enregistrer un commentaire