用原型實例指定建立物件的種類,並透過拷貝這些原型建立新物件。
場景中大量相似敵人(相同技能、模型),唯位置與能力值異。若為每種能力建立子類,將爆炸性增加類別數。且步兵模型初始化極耗時。解決方案:建立單一原型 → 複製多份 → 微調屬性。
using System;
using System.Threading;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;
namespace PrototypeExample
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Enemy enemyPrototype = new FootMan(5, 4, new Location(100, 200));
GameScene gs = new GameScene();
List<Enemy> enemyGroup = gs.CreateEnemyGroup(enemyPrototype);
foreach (FootMan ft in enemyGroup)
{
ft.ShowInfo();
ft.FootmanAttack();
}
Console.WriteLine(sw.ElapsedMilliseconds);
}
}
class GameScene
{
public List<Enemy> CreateEnemyGroup(Enemy enemyPrototype)
{
var group = new List<Enemy>();
Enemy e1 = enemyPrototype.Clone(true);
e1.Location.x = enemyPrototype.Location.x - 10;
Enemy e2 = enemyPrototype.Clone(true);
e2.Location.x = enemyPrototype.Location.x + 10;
Enemy elite = enemyPrototype.Clone(true);
elite.Power = enemyPrototype.Power * 2;
elite.Speed = enemyPrototype.Speed * 2;
elite.Location.x = enemyPrototype.Location.x;
elite.Location.y = enemyPrototype.Location.y + 10;
group.Add(e1); group.Add(e2); group.Add(elite);
return group;
}
}
[Serializable]
class Location { public int x, y; public Location(int x, int y) { this.x = x; this.y = y; } }
[Serializable]
abstract class Enemy
{
protected Location location;
public Location Location { get { return location; } set { location = value; } }
protected int power;
public int Power { get { return power; } set { power = value; } }
protected int speed;
public int Speed { get { return speed; } set { speed = value; } }
public abstract Enemy Clone(bool isDeepCopy);
public abstract void ShowInfo();
public Enemy(int power, int speed, Location location)
{
Thread.Sleep(1000); // 模擬高運算建構
this.power = power; this.speed = speed; this.location = location;
}
}
[Serializable]
class FootMan : Enemy
{
private string model;
public FootMan(int power, int speed, Location location) : base(power, speed, location)
{ model = "footman"; }
public override void ShowInfo()
{
Console.WriteLine($"model:{model} power:{power} speed:{speed} location:({location.x},{location.y})");
}
public override Enemy Clone(bool isDeepCopy)
{
FootMan footman;
if (isDeepCopy)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, this);
ms.Position = 0;
footman = (FootMan)formatter.Deserialize(ms);
}
else
footman = (FootMan)this.MemberwiseClone();
return footman;
}
public void FootmanAttack() => Console.WriteLine("FootmanAttack");
}
}
[Serializable] 標記支援二進位序列化深拷貝Stopwatch 精確測量建構 vs 複製效能差異Enemy 抽象