範例:世紀帝國(抽象工廠模式)

Pattern: 抽象工廠模式

Class Diagram: 世紀帝國


情境:根據用戶端對兵種的需求,我們要生產對應的軍事單位

這邊我們省略軍事單位的定義。
可參考範例:世紀帝國(簡單工廠模式)

  • 定義裝備工廠
1
2
3
4
5
6
7
8
9
10
using DotNetCoreKata.DomainModels.AgeOfEmpires.Transportation;
using DotNetCoreKata.DomainModels.AgeOfEmpires.Weapon;

namespace DotNetCoreKata.DomainModels;

public interface IEquipmentFactory
{
IWeapon CreateWeapon();
ITransportation CreateTransportation();
}
  • 定義民兵裝備工廠
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using DotNetCoreKata.DomainModels.AgeOfEmpires.Transportation;
using DotNetCoreKata.DomainModels.AgeOfEmpires.Weapon;

namespace DotNetCoreKata.DomainModels.AgeOfEmpires;

public class MilitiaEquipmentFactory : IEquipmentFactory
{
public ITransportation CreateTransportation()
{
return new Legs();
}

public IWeapon CreateWeapon()
{
return new Stick();
}
}
  • 定義弓兵裝備工廠
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using DotNetCoreKata.DomainModels.AgeOfEmpires.Transportation;
using DotNetCoreKata.DomainModels.AgeOfEmpires.Weapon;

namespace DotNetCoreKata.DomainModels.AgeOfEmpires;

public class ArcherEquipmentFactory: IEquipmentFactory
{
public IWeapon CreateWeapon()
{
return new Bow();
}
public ITransportation CreateTransportation()
{
return new Legs();
}
}
  • 定義騎士裝備工廠
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using DotNetCoreKata.DomainModels.AgeOfEmpires.Transportation;
using DotNetCoreKata.DomainModels.AgeOfEmpires.Weapon;

namespace DotNetCoreKata.DomainModels.AgeOfEmpires;

public class KnightEquipmentFactory : IEquipmentFactory
{
public ITransportation CreateTransportation()
{
return new Horse();
}

public IWeapon CreateWeapon()
{
return new Sword();
}
}

  • 客戶端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using DotNetCoreKata.DomainModels;
using DotNetCoreKata.DomainModels.AgeOfEmpires;
using DotNetCoreKata.Enums;

namespace DotNetCoreKata.Services.AgeOfEmpires;

public class Client : IClient
{
public IUnit Train(UnitCategory unitCategory)
{
Console.Write($"Ask resources to build unit: {unitCategory}.");

IEquipmentFactory equipmentFactory = unitCategory switch
{
UnitCategory.Military => new MilitiaEquipmentFactory(),
UnitCategory.Archer => new ArcherEquipmentFactory(),
UnitCategory.Knight => new KnightEquipmentFactory(),
_ => new MilitiaEquipmentFactory()
};

return new Unit(equipmentFactory.CreateWeapon(), equipmentFactory.CreateTransportation());
}
}

ʕ •ᴥ•ʔ:重讀一次 Design Pattern,改用 C# 來寫範例。

Share