tags:

views:

104

answers:

4

What is your opinion about my code ?

#ifndef PROTOTYPE_H
#define PROTOTYPE_H

#include <map>

// =============================================
class prototype
{
public:
 prototype();
 ~prototype();

 virtual prototype* clone(prototype* ) = 0;
 virtual void initialize(const bool&, const int&, 
  const std::string& ) = 0;

 virtual bool getHasTurbo() const = 0 ;
 virtual int getCapacity()  const = 0;
 virtual const std::string& getCategory() const = 0;

 virtual void display() const = 0;
};
// =============================================
#endif

#include "Prototype.h"

// =============================================
prototype::prototype()
{
}
// =============================================
prototype::~prototype()
{
}

#ifndef VEHICLE_PROTOTYPE_H
#define VEHICLE_PROTOTYPE_H

#include "Prototype.h"
#include <string>


// ==============================================
class vehiclePrototype : public prototype
{
public:
 vehiclePrototype();
 vehiclePrototype(const bool&, const int&, 
  const std::string&);

 vehiclePrototype(prototype* );
 ~vehiclePrototype();

 prototype* clone(prototype* );
 void initialize(const bool&, const int&, 
  const std::string& );

 bool getHasTurbo() const;
 int getCapacity() const;
 const std::string& getCategory() const;

 void display() const ;
private:
 int capacity;
 bool hasTurbo;

 std::string category;



};
// =============================================
#endif

#include "VehiclePrototype.h"

#include <iostream>

// =============================================
vehiclePrototype::vehiclePrototype() 
 : capacity(0), hasTurbo(bool() ), 
 category(std::string() ) 
{
}
// =============================================
vehiclePrototype::vehiclePrototype(const bool& userHasTurbo, 
  const int& userCapacity, 
  const std::string& userCategory)
{
 hasTurbo = userHasTurbo;
 capacity = userCapacity;

 category = userCategory;
}
// ============================================
vehiclePrototype::vehiclePrototype(prototype* rhs)
{
 hasTurbo = rhs->getHasTurbo();
 capacity = rhs->getCapacity();
 category = rhs->getCategory();  
}
// ============================================
vehiclePrototype::~vehiclePrototype() 
{
}
// =============================================
prototype* vehiclePrototype::clone(prototype* myPrototype)
{
 return new vehiclePrototype(myPrototype); 
}
// =============================================
void vehiclePrototype::initialize(const bool& userHasTurbo, 
        const int& userCapacity, 
        const std::string& userCategory)
{
 hasTurbo = userHasTurbo;
 capacity = userCapacity;

 category.assign(userCategory);
}
// =============================================
bool vehiclePrototype::getHasTurbo() const
{
 return hasTurbo;
} 
// =============================================
int vehiclePrototype::getCapacity() const
{
 return capacity;
}
// =============================================
const std::string& vehiclePrototype::getCategory() const
{
 return category;
}
// =============================================
void vehiclePrototype::display() const
{
 std::cout << std::boolalpha 
  << "Car Specification\n" 
  << "Vehicle Category Type : " << getCategory() << "\n"
  << "Vehicle Capacity : " << getCapacity() << "\n"
  << "Vehicle Turbo : " << getHasTurbo() << "\n";
}
// =============================================


#ifndef PROTOTYPE_MANAGER_H
#define PROTOTYPE_MANAGER_H

#include <map>
#include <vector>



class prototype;

// =============================================
class prototypeManager
{
public:
 typedef std::map<int, prototype* > prototypeMap;
 typedef std::map<int, prototype* >::iterator prototypeMapIte;

 typedef std::vector<prototype*> prototypeVec;

public:
 prototypeManager();
 ~prototypeManager();

 prototype* createVehicle(int, const bool&, 
  const int&, const std::string& );

 void populateVehicle();

 // To create a specific instance of a class
 // without coding the class
 void registerVehicle( const bool&, 
  const int&, const std::string&);
 void registerVehicle(const int&, const bool&, 
  const int&, const std::string&);
 void unRegisterVehicle(int);

private:
 static int vehicleType;

 prototypeMap registry;

 // Static Product
 // Empty Prototype
 prototype* obj;
 prototype* sedan, *superCar, *f1Car;

 // Dynamic Product
 prototypeVec cont;



};
// =============================================
#endif


#include "PrototypeManager.h"
#include "VehiclePrototype.h"

#include <iostream>

// =============================================
int prototypeManager::vehicleType = 1;
// =============================================
prototypeManager::prototypeManager()
 : registry(prototypeMap()), obj(new vehiclePrototype), 
 sedan(new vehiclePrototype(false, 1600, "B Class") ), 
 superCar(new vehiclePrototype(true, 3000, "D Class") ), 
 f1Car(new vehiclePrototype(true, 6000, "F Class") ), 
 cont(prototypeVec() )

{
 populateVehicle();
}
// =============================================
prototypeManager::~prototypeManager()
{
 delete obj;
 delete sedan;
 delete superCar;
 delete f1Car;

 obj = 0;
 sedan = 0;
 superCar = 0;
 f1Car = 0;

 for (size_t loop = 0;loop<cont.size();++loop)
 {
  delete cont[loop];
  cont[loop] = 0;
 }

}
// =============================================
prototype* prototypeManager::createVehicle(
       int uservehicleType, 
       const bool& userHasTurbo, 
       const int& userCapacity, 
       const std::string& userCategory)
{
 prototypeMapIte myIte = registry.find(uservehicleType);
 prototype* instance = 0;

 if (myIte == registry.end() )
 {
  // Register Vehicle
  registerVehicle(uservehicleType, userHasTurbo, 
   userCapacity, userCategory);

  myIte = registry.find(uservehicleType);
  prototype* temp = myIte->second;
  instance = obj->clone(temp);
  instance->initialize(userHasTurbo, userCapacity, 
  userCategory);


 }
 else
 {
  prototype* temp = myIte->second;
  instance = obj->clone(temp);
  instance->initialize(userHasTurbo, userCapacity, 
  userCategory);
 }

 std::cout << "\nClone Vehicle\n";

 return instance;
}
// =============================================
void prototypeManager::populateVehicle()
{
 registry.insert(prototypeMap::value_type(vehicleType, sedan) );
 ++vehicleType;

 registry.insert(prototypeMap::value_type(vehicleType, superCar) );
 ++vehicleType;

 registry.insert(prototypeMap::value_type(vehicleType, f1Car) );
 ++vehicleType; 
}
// =============================================
void prototypeManager::registerVehicle(
      const bool& userHasTurbo, 
      const int& userCapacity, 
      const std::string& userCategory)
{
 prototype* temp = new vehiclePrototype(userHasTurbo, 
  userCapacity, userCategory); 

 cont.push_back(temp);
 registry.insert(prototypeMap::value_type(vehicleType, temp) );
 ++vehicleType;

 std::cout << "\nRegister new Vehicle Type " 
  <<vehicleType << "\n";
}
// =============================================
void prototypeManager::registerVehicle(const int& userVehicleTpye, 
      const bool& userHasTurbo, 
      const int& userCapacity, 
      const std::string& userCategory)
{
 prototype* temp = new vehiclePrototype(userHasTurbo, 
  userCapacity, userCategory); 

 cont.push_back(temp);
 registry.insert(prototypeMap::value_type(userVehicleTpye, temp) );

 std::cout << "\nRegister new Vehicle Type " 
  <<userVehicleTpye << "\n";
}
// =============================================
void prototypeManager::unRegisterVehicle(int vehicleType)
{
 prototype* removePrototype = registry.find(vehicleType)->second;
 registry.erase(vehicleType);

 std::cout << "\nUnRegister Vehicle Type " 
  << vehicleType << "\n";
}
// =============================================

#include <iostream>

using namespace std;

#include "Prototype.h"
#include "VehiclePrototype.h"
#include "PrototypeManager.h"

// =============================================

// =============================================

// =============================================
int main()
{
 prototypeManager obj;
 prototype* myCar;

 myCar = obj.createVehicle(1, false, 1300, "B Class");
 myCar->display();

 myCar = obj.createVehicle(2, true, 3200, "D Class");
 myCar->display();

 myCar = obj.createVehicle(5, false, 2500, "E Class"); 
 myCar->display();

 obj.unRegisterVehicle(1);
 myCar = obj.createVehicle(1, false, 1600, "B Class");
 myCar->display();

 return 0;
}

How to dynamic loading in C++ ? I read the Gof book and i don;t understand the third consequences (pg 120) specifying new object by varying structure. Please explain.

Thanks.

A: 

I don't see any dynamic loading stuff in there.

tojas
My question is regards to the topic.
peterwkc
+3  A: 

What is your opinion about my code ?

This isn't a code review site, and questions and answers are meant to be objective, so I'll just mention a couple of issues with the code. In general, you should ask questions about specific problems you're having, and only post the code needed to describe or reproduce the problem.

The only error I can see (after briefly reading through) is that prototype needs a virtual destructor, otherwise it's invalid to delete instances of derived classes via base class pointers (as the destructor of prototypeManager does).

Stylistically, there are a few bits of unnecessary code. prototype doesn't need a constructor; the implicit one is just fine. It does need a destructor (virtual, as mentioned above); since this will be empty, there's no reason not to put it inline in the class declaration. In your initialisation list, category(std::string()) could be category(), or omitted entirely; hasTurbo(bool()) likewise could be hasTurbo(), or hasTurbo(false) if you want to be explicit. EDIT: Also, there's no need to nullify the pointers after deleting them in the destructor. None of these are particularly bad (and are sometimes necessary if you have to follow a braindead coding style), but they do make the code slightly harder to follow.

How to dynamic loading in C++ ?

I don't know what you mean by "dynamic loading", or how it relates to the code or the Prototype pattern. Perhaps if you explain what you want to achieve, someone can help.

I read the Gof book and i don;t understand the third consequences (pg 120) specifying new object by varying structure. Please explain.

Assuming you have the same edition as me, that passage says that you can compose simple objects into complex composite objects and, as long as the composite object implements the Prototype interface correctly, the new objects can be used alongside the old ones. It doesn't go into much detail about how to do that, but the Composite pattern might be useful for some applications. In your example, you could imagine being able to take some simple components (wheels, engines, doors, fluffy dice, etc) and combine them into a new vehicle; as long as that vehicle is properly clonable, then it can be used just like the existing prototypes.

Mike Seymour
@Mike, You have actually answers my question. Thanks.
peterwkc
A: 

I would add a cont.clear() after the for loop in ~prototypeManager.
I don't like very much the current createVehicle function. It seems it may deliver flexibility issues. If the implementation changes in a future, how much of your code would you have to change? Maybe a constructor plus setter functions would be a better easy option. Regarding to this, and seeing you are having a look at design patterns, this example is probably fit for using a Factory pattern.

rturrado
There's no point clearing a container that's about to be destroyed, unless you're being paid per line of code.
Mike Seymour
You may be right because when changing the clone() method interface, it may reflect the create vehicle() method.
peterwkc
A: 

//subjective

What is your opinion about my code ?

It can be improved in many places.

~prototype();

Destructor should be virtual

virtual prototype* clone(prototype* ) = 0;

Omitted argument names. Bad idea. Parameter names automatically document your code and their names are supposed to explain their meaning. Also, they are used in autocomplete/intellisense features, so removing them is really a bad taste.

std::string

Using something like "typedef std::string Str" will make your code shorter

virtual prototype* clone(prototype* ) = 0;

Doesn't make sense. If you wanted to make copy of current object, you should have used no parameter and this should have been const. If you wanted to turn this object into copy of object given in argument (really bad idea - they could be incompatible, in which case clone should be called assign), you should have used const argument and function should have been void (or it could return Reference). Or if you wanted generic routine for copying objects, it should have been static.

virtual void initialize(const bool&, const int&, const std::string& )

bool and int are "small" types so using const reference them is pointless.

prototype::prototype()
{
}

There are no fields in base class, so you don't need a constructor

hasTurbo(bool() ), category(std::string() )

Why? Just provide default values, you don't need to give bool() or std::string(). Or don't provide any constructor at all. std::string will be automatically initialized to empty string. Giving it another std::string is waste of characters in your file.

hasTurbo = userHasTurbo; // in constructor

This can be done using :hasTurbo(userHasTurbo). It doesn't make sense to call assignment unless you have to calculate value during contstructor.

class prototype

It makes sense to use different name format for classes, methods and variables. In my code all class names start with uppercase letter (class Prototype). variables and methods start with lowercase letter (void Prototype::doSomething).This allows to create instance of class using same name (i.e. Prototype protype). I think Qt 4 uses somewhat similar scheme.

typedef std::map<int, prototype* > prototypeMap;

Code like this rasies questions like "who is going to delete all prototype pointer". It is better to use smart pointers instead of prototype*.

typedef std::map<int, prototype* >::iterator prototypeMapIte;

You don't really need that you could use prototypeMap::iterator.

for (size_t loop = 0;loop<cont.size();++loop)
 {
  delete cont[loop];
  cont[loop] = 0;
 }

And this is why you need smart pointers - you could just call clear() if you used smart pointers.. Also you don't need to set objects to zero. you're in destructor, so nobody will try to access them anymore anyway.

prototype* temp = myIte->second;
instance = obj->clone(temp);

It should be "instance = obj->clone()" or "instance = Prototype::clone(obj)". Otherwise the logic if ambiguous - you use one object to make copy of another object of same type. Things like this introduce subtle deadly ninja bugs.

registry.insert(prototypeMap::value_type(vehicleType, sedan) );
++vehicleType;

prototypeMap has size() paramters that could be used instead of vehicleType - in THIS case and if map was intialized just once. Also the proper use would be prototypeMap[vehicleType] = sedan.

 std::cout << "\nRegister new Vehicle Type " <<vehicleType << "\n";

I believe that proper way would be to use std::endl instead of \n. Unix and Windows use different line endings.

 registry.erase(vehicleType);

Could cause memory leak if prototype used in map was created outside of class.

How to dynamic loading in C++ ?

You need Prototype pattern. Every class derived from base Prototype class should have method clone() const; (with NO arguments) which will return copy of current class. Make a map, fill it with empty objects corresponding for each id. If object found in map, call clone, return new copy, and call virtual load() method. This way you'll get "dynamic loading".

SigTerm
myIte = registry.find(uservehicleType); prototype* temp = myIte->second; instance = obj->clone(temp);No i need to clone another object and not the current class object. I need to clone based on the vehicle type selected by user in create vehicle function, it may clone itself or its one of the subclass which it depends on the temp which has prototype interface. Your approach is to clone itself using this pointer. My approach is clone based on the vehicle type find from the map.
peterwkc
I wonder it is a must to clone itself because i need flexibility to select which to clone.
peterwkc
prototype* temp = myIte->second;instance = obj->clone(temp);It should be "instance = obj->clone()" or "instance = Prototype::clone(obj)". Otherwise the logic if ambiguous - you use one object to make copy of another object of same type. The reason is i need to clone based on the user selected vehicle type. Do you have any better suggestion ?
peterwkc
My latest question is at http://stackoverflow.com/questions/3131302/c-prototype-and-dynamic-loading
peterwkc
(c) captain obvious: "i need to clone another object and not the current class object" introduce virtual clone method into other class. It will return a copy of other class (casted into Prototype*), no matter what the other class is. " My approach is clone based on the vehicle type" the correct approach is to take class from the map and clone it.
SigTerm
@peterwkc: You need more C++ training (few months, I think). It looks like you don't exactly understand polymorphism ( http://www.cplusplus.com/doc/tutorial/polymorphism/ ) and how virtual methods work, which is causing you problems. You will not be able to implement Prototype class correctly, until you get good understanding of those concepts. Grab any C++ book or OOP tutorials, do some programming for a few months, and you should eventually get it. Your first priority is to get understanding of OOP, virtual methods, and polymorphism. When you're done with that, you can try GoF patterns.
SigTerm
"My latest question is": I'll reply to question only if I bump into it (no invitations), and find it interesting. I already highlighted a few problems in your code, if you want to improve your skills - deal with those problems. IMO, you simply need more C++ practice first.
SigTerm
As you pointed out, my logic seems a bit weird and your logic seems reasonable - for a class to clone itself. But think in manufacturing environment, a customer takes a prototype A and ask you to clone prototype B to him where the prototype A and B have common interface. I think i should encapsulate the user choice using another pattern. Any suggestion ?
peterwkc
"a customer takes a prototype A and ask you to clone prototype B" Then you return B::clone(). There is no need for prototype A at all.
SigTerm