C ++原型和动态加载

时间:2010-06-28 09:32:26

标签: c++

您对我的代码有何看法?

#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;
}

如何在C ++中动态加载? 我阅读了Gof书,但我不理解通过改变结构来指定新对象的第三种结果(第120页)。请解释。

感谢。

4 个答案:

答案 0 :(得分:3)

  

您对我的代码有什么看法?

这不是代码审查网站,问题和答案是客观的,所以我只提到代码的几个问题。一般来说,您应该询问有关您遇到的具体问题的问题,并且只发布描述或重现问题所需的代码。

我能看到的唯一错误(在简要阅读之后)是prototype需要一个虚拟析构函数,否则通过基类指针删除派生类的实例是无效的(作为prototypeManager的析构函数一样)。

在风格上,有一些不必要的代码。 prototype不需要构造函数;隐含的就好了。它确实需要一个析构函数(虚拟,如上所述);因为这将是空的,所以没有理由不将它内联在类声明中。在您的初始化列表中,category(std::string())可以是category(),也可以完全省略; hasTurbo(bool())同样可以hasTurbo(),或hasTurbo(false),如果你想要明确的话。编辑:此外,没有必要在析构函数中删除它们之后使指针无效。这些都不是特别糟糕(如果你必须遵循脑死亡编码风格,有时是必要的),但它们确实使代码更难以遵循。

  

如何在C ++中动态加载?

我不知道“动态加载”是什么意思,或者它与代码或Prototype模式的关系。也许如果你解释你想要实现的目标,有人可以提供帮助。

  

我读了Gof书,但我不理解通过改变结构来指定新对象的第三种结果(第120页)。请解释一下。

假设您拥有与我相同的版本,该段落说您可以将简单对象组合成复杂的复合对象,并且只要复合对象正确实现Prototype接口,新对象就可以与旧对象一起使用。它没有详细说明如何做到这一点,但Composite模式可能对某些应用程序有用。在你的例子中,你可以想象能够采取一些简单的组件(轮子,引擎,门,蓬松的骰子等)并将它们组合成一辆新车;只要该车辆可以正确克隆,就可以像现有原型一样使用。

答案 1 :(得分:0)

我没有看到任何动态加载内容。

答案 2 :(得分:0)

我会在cont.clear()的for循环之后添加~prototypeManager 我不太喜欢当前的createVehicle函数。它似乎可能带来灵活性问题。如果实施在未来发生变化,您需要更改多少代码?也许构造函数和setter函数是一个更好的选择。关于这一点,并且看到你正在研究设计模式,这个例子可能适合使用工厂模式。

答案 3 :(得分:0)

//主观

  

您对我的代码有什么看法?

它可以在很多地方得到改善。

  

〜原型();

析构函数应该是虚拟的

  

虚拟原型* clone(prototype *)= 0;

省略的参数名称。馊主意。参数名称会自动记录您的代码,它们的名称应该解释它们的含义。此外,它们用于自动完成/智能感知功能,因此删除它们确实是一种不好的味道。

  

的std :: string

使用类似“typedef std :: string Str”的东西会缩短你的代码

  

虚拟原型* clone(prototype *)= 0;

没有意义。如果你想复制当前对象,你应该使用没有参数,这应该是const。如果你想把这个对象变成参数中给出的对象的副本(真的很糟糕 - 它们可能是不兼容的,在这种情况下克隆应该被称为assign),你应该使用const参数并且函数应该是无效的(或者它可以返回参考)。或者,如果您想要复制对象的通用例程,它应该是静态的。

  

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

bool和int是“小”类型,所以使用const引用它们是没有意义的。

prototype::prototype()
{
}

基类中没有字段,因此您不需要构造函数

  

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

为什么呢?只需提供默认值,您不需要提供bool()或std :: string()。或者根本不提供任何构造函数。 std :: string将自动初始化为空字符串。给它另一个std :: string会浪费你文件中的字符。

  

hasTurbo = userHasTurbo; //在构造函数中

这可以使用:hasTurbo(userHasTurbo)来完成。除非你必须在构造函数中计算值,否则调用赋值是没有意义的。

  

类原型

对类,方法和变量使用不同的名称格式是有意义的。在我的代码中,所有类名都以大写字母(类Prototype)开头。变量和方法以小写字母开头(void Prototype :: doSomething)。这允许使用相同的名称创建类的实例(即Prototype原型)。我认为Qt 4使用了类似的方案。

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

代码就像这样的rasies问题,例如“谁将要删除所有原型指针”。最好使用智能指针而不是原型*。

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

你真的不需要使用prototypeMap :: iterator。

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

这就是你需要智能指针的原因 - 如果你使用了智能指针,你可以调用clear()。你也不需要将对象设置为零。你是在析构函数中,所以无论如何都没有人会试图访问它们。

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

应该是“instance = obj-&gt; clone()”或“instance = Prototype :: clone(obj)”。否则逻辑如果不明确 - 您使用一个对象来复制另一个相同类型的对象。这样的事情会引入微妙的致命忍者虫。

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

prototypeMap有size()参数,可以用来代替vehicleType - 在这种情况下,如果map只初始化一次。 正确使用的还有prototypeMap [vehicleType] = sedan。

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

我认为正确的方法是使用std :: endl而不是\ n。 Unix和Windows使用不同的行结尾。

 registry.erase(vehicleType);

如果地图中使用的原型是在课外创建的,可能会导致内存泄漏。

  

如何在C ++中动态加载?

你需要原型模式。从基础Prototype类派生的每个类都应该有方法clone()const; (没有参数)将返回当前类的副本。制作一张地图,用每个id对应的空对象填充它。如果在map中找到对象,则调用clone,返回新副本,并调用virtual load()方法。这样你就可以获得“动态加载”。