用原型實例指定創建對象種類,透過拷貝原型創建新對象。
遊戲場景大量相似敵人:技能相同,位置不同導致能力微調。需組 3 步兵 + 1 精英步兵。若為每種能力建子類 → 子類爆炸;且步兵模型初始化極耗時。只建一個原型,複製後微調位置/能力 → Prototype 模式。
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 => location; set => location = value; }
protected int power;
public int Power { get => power; set => power = value; }
protected int speed;
public int Speed { get => 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
{
string model = "footman";
public FootMan(int power, int speed, Location location) : base(power, speed, location) { }
public override void ShowInfo() => Console.WriteLine($"model:{{0}} power:{{1}} speed:{{2}} location:({{3}},{{4}})", model, power, speed, location.x, location.y);
public override Enemy Clone(bool isDeepCopy)
{
FootMan fm;
if (isDeepCopy)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
fm = (FootMan)bf.Deserialize(ms);
}
}
else fm = (FootMan)MemberwiseClone();
return fm;
}
public void FootmanAttack() => Console.WriteLine("FootmanAttack");
}
}
ShowInfo、抽象 Clone。Clone(bool) 參數決定深/淺拷貝:true 用序列化反序列化深拷貝(含引用類型完整複製),false 用 MemberwiseClone 淺拷貝。Location 實例則位置無法分離,故須深拷貝確保獨立。Thread.Sleep(1000) 模擬耗時初始化;克隆僅耗 1 次初始化時間,體現效能優勢。MemberwiseClone 淺拷貝、序列化反序列化深拷貝(代價較大),視情況選擇。