游戏设计模式-原型模式

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

原型模式的核心思想是:一个对象可以生成与自身相似的其他对象。假设我们有一个怪物的类,我们可以这样构造:

#include 

class Enemy
{
public:
	virtual ~Enemy() {}
	virtual std::shared_ptr Clone() = 0;
};

class BirdEnemy :public Enemy
{
public:
	BirdEnemy(){}
	BirdEnemy(float hp, float speed) :
		hp(hp), speed(speed) {}

	virtual std::shared_ptr  Clone()
	{
		return std::make_shared< BirdEnemy>(100, 20);
	}

private:
	float hp = 0;
	float speed = 0;
};

然后我们定义一个生成器

class Spawner
{
public:
	virtual ~Spawner() {}
	virtual std::shared_ptr SpawnEnemy() = 0;
};

template
class SpawnFor : public Spawner
{
public:
	virtual std::shared_ptr SpawnEnemy() { return std::make_shared(); }
};

使用

auto bird_spawner = std::make_shared>();

如果我们想要创建各种各样的BirdEnemy,则只需要创建各种各样的原型。我们只需要对上面的代码进行简单的更改:

class Enemy
{
public:
	virtual ~Enemy() {}
	virtual std::shared_ptr Clone() = 0;
};

class BirdEnemy :public Enemy
{
public:
	BirdEnemy(){}
	BirdEnemy(const BirdEnemy& be) :hp(be.hp), speed(be.speed) {}
	BirdEnemy(BirdEnemy&& be) :hp(be.hp), speed(be.speed) {}
	BirdEnemy(float hp, float speed) :
		hp(hp), speed(speed) {}

	virtual std::shared_ptr  Clone()
	{
		return std::make_shared< BirdEnemy>(*this);
	}

private:
	float hp = 0;
	float speed = 0;
};

class Spawner
{
public:
	virtual ~Spawner() {}
	virtual std::shared_ptr SpawnEnemy() = 0;
};

template
class SpawnFor : public Spawner
{
public:
	SpawnFor(T&& t) :t(std::move(t)) {}
	virtual std::shared_ptr SpawnEnemy() { return t.Clone(); }

private:
	T t;
};

现在策划告诉我们需要一个血量为100,速度为20的鸟类怪物,只需要:

BirdEnemy brid_enemy_template(100, 20);
auto bird_spawner = std::make_shared>(std::move(brid_enemy_template));

甚至下一步,可以直接将这些数值和种类都配置在表格里,代码进行循环读取,并创建各种各样的生成器。


以上都是基于C++来进行的设计,但是对于很多将Class作为头等公民的语言来说,Class是可以当做参数进行传递的,对于上面的实现,将会更加的简洁和优雅。

你可能感兴趣的:(游戏服务器,服务器,原型模式,游戏,c++)