商店 (Shop) 使用不同車輛建造者 (VehicleBuilder) 依序構建車架、引擎、車輪、車門,產出機車、汽車、速克達。
using System;
using System.Collections;
// 指導者
class Shop
{
public void Construct(VehicleBuilder vb)
{
vb.BuildFrame();
vb.BuildEngine();
vb.BuildWheels();
vb.BuildDoors();
}
}
// 抽象建造者
abstract class VehicleBuilder
{
protected Vehicle vehicle;
public Vehicle Vehicle => vehicle;
public abstract void BuildFrame();
public abstract void BuildEngine();
public abstract void BuildWheels();
public abstract void BuildDoors();
}
// 具體建造者:機車
class MotorCycleBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle = new Vehicle("MotorCycle");
vehicle["frame"] = "MotorCycle Frame";
}
public override void BuildEngine() => vehicle["engine"] = "500 cc";
public override void BuildWheels() => vehicle["wheels"] = "2";
public override void BuildDoors() => vehicle["doors"] = "0";
}
// 具體建造者:汽車
class CarBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle = new Vehicle("Car");
vehicle["frame"] = "Car Frame";
}
public override void BuildEngine() => vehicle["engine"] = "2500 cc";
public override void BuildWheels() => vehicle["wheels"] = "4";
public override void BuildDoors() => vehicle["doors"] = "4";
}
// 具體建造者:速克達
class ScooterBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle = new Vehicle("Scooter");
vehicle["frame"] = "Scooter Frame";
}
public override void BuildEngine() => vehicle["engine"] = "none";
public override void BuildWheels() => vehicle["wheels"] = "2";
public override void BuildDoors() => vehicle["doors"] = "0";
}
// 產品
class Vehicle
{
private string type;
private Hashtable parts = new Hashtable();
public Vehicle(string type) => this.type = type;
public object this[string key]
{
get => parts[key];
set => parts[key] = value;
}
public void Show()
{
Console.WriteLine(" ---------------------------");
Console.WriteLine($"Vehicle Type: {type}");
Console.WriteLine($" Frame : {parts["frame"]}");
Console.WriteLine($" Engine : {parts["engine"]}");
Console.WriteLine($" #Wheels: {parts["wheels"]}");
Console.WriteLine($" #Doors : {parts["doors"]}");
}
}
// 客戶端
public class BuilderApp
{
public static void Main()
{
Shop shop = new Shop();
VehicleBuilder b1 = new ScooterBuilder();
VehicleBuilder b2 = new CarBuilder();
VehicleBuilder b3 = new MotorCycleBuilder();
shop.Construct(b1); b1.Vehicle.Show();
shop.Construct(b2); b2.Vehicle.Show();
shop.Construct(b3); b3.Vehicle.Show();
}
}
--------------------------- Vehicle Type: Scooter Frame : Scooter Frame Engine : none #Wheels: 2 #Doors : 0 --------------------------- Vehicle Type: Car Frame : Car Frame Engine : 2500 cc #Wheels: 4 #Doors : 4 --------------------------- Vehicle Type: MotorCycle Frame : MotorCycle Frame Engine : 500 cc #Wheels: 2 #Doors : 0
Shop.Construct() 確保 Frame→Engine→Wheels→DoorsTruckBuilder 只需實作四個方法,不動既有代碼