设计模式之原型模式(Prototype)
与之前的享元模式有一些共通之处,享元模式是所有相同对象共享同一份数据,比如森林场景里有大树和树苗,不需要为棵树处理一份数据,因为数据是固定不变的,大树和树苗各有一份原始数据,所有的实体都引用这份数据即可。
而原型模式,是用一份原始数据作为原型,克隆出相同或近似的数据,克隆数据可能会单独处理,但原型不变。比如场景中有普通战士哥布林、射手哥布林、法师哥布林,为每种哥布林创建一个原型,分别利用原型生产出一定数量的战士、射手、法师(初始化伤害、防御、血量),在战斗场景每个哥布林再做战斗数值计算。
下面是根据《Game.Programming.Patterns》一书对原型模式的理解:
//怪物基类
public class Monster
{
protected int health;
protected int speed;
public virtual void Init(int _health, int _speed)
{
health = _health;
speed = _speed;
}
}
//怪物对象子类
public class Ghost : Monster
{
private int attack;
}
//生产者基类
public abstract class Spawner
{
//可二选一
public abstract Monster SpawnMonster();
public abstract Monster SpawnMonster(int _health, int _speed);
}
//生产者类,有一个怪物类作为模板,即原型,用于生成更多的同类怪物
public class SpawnerFor<T> : Spawner where T : Monster, new()
{
public override Monster SpawnMonster()
{
return new T();
}
public override Monster SpawnMonster(int _health, int _speed)
{
T t = new T();
t.Init(_health, _speed);
return t;
}
}
public class PrototypeDemo : MonoBehaviour
{
void Start()
{
//创建某类怪物的生产者
Spawner ghostSpawner = new SpawnerFor<Ghost>();
//生产怪物
Ghost newGhost = ghostSpawner.SpawnMonster() as Ghost;
Ghost normalGhost = ghostSpawner.SpawnMonster(10, 5) as Ghost;
Ghost fastGhost = ghostSpawner.SpawnMonster(10, 10) as Ghost;
}
}