游戏中的原型模式

“使用特定原型实例来创建特定种类的对象,并且通过拷贝原型来创建新的对象。”

例如我们游戏中有3种怪物,幽灵、恶魔、术士

class Monster 
{ 
 // Stuff... 


}; 

class Ghost : public Monster {}; 
class Demon : public Monster {}; 
class Sorcerer : public Monster {}; 

需要有Monster生成器

class Spawner 
{
public:  
 virtual ~Spawner() {} 
 virtual Monster* spawnMonster() = 0;
}; 

class GhostSpawner : public Spawner 
{ 
public: 
 virtual Monster* spawnMonster() 
 { 
  return new Ghost(); 
 } 
}; 

class DemonSpawner : public Spawner 
{
public:  
 virtual Monster* spawnMonster() 
 {  
  return new Demon();  
 } 
}; 

// ...

这样太复杂了,代码量也多,可以抽象clone方法解决

class Monster 
{ 
public: 
 virtual ~Monster() {} 
 virtual Monster* clone() = 0;  

 // Other stuff... 

};

class Ghost : public Monster {
public:  
 Ghost(int health, int speed)  
 : health_(health),   
  speed_(speed)  
 {}  

 virtual Monster* clone()  
 {  
  return new Ghost(health_, speed_);  
 } 

private:  
 int health_;  
 int speed_; 
}

生成器也可以抽象出成为一个了

class Spawner 
{ 
public:  
  Spawner(Monster* prototype)  
  : prototype_(prototype)
  {}  

  Monster* spawnMonster()  
  {   
   return prototype_>clone(); 
  } 
private: 
  Monster* prototype_; 
};

Monster* ghostPrototype = new Ghost(15, 3); 
Spawner* ghostSpawner = new Spawner(ghostPrototype);

生成器函数

把创建原型的行为也交给生成器来做,提供创建原型的函数

Monster* spawnGhost()
{  
  return new Ghost(); 
}

typedef Monster* (*SpawnCallback)();

class Spawner 
{
public:  
  Spawner(SpawnCallback spawn)  
  : spawn_(spawn)
{}  

  Monster* spawnMonster() { return spawn_(); } 

private: 
  SpawnCallback spawn_;
};

Spawner* ghostSpawner = new Spawner(spawnGhost);

使用C++模板

class Spawner 
{
public: 
 virtual ~Spawner() {}  
 virtual Monster* spawnMonster() = 0;
}; 

template <class T> 
class SpawnerFor : public Spawner 
{
public: 
 virtual Monster* spawnMonster() { return new T(); }
};

Spawner* ghostSpawner = new SpawnerFor<Ghost>();

编程范式

对于哪些不用OOP的,如JavaScript的原型链,则需要不同的思考与设计。