C# Фабричний метод (Factory Method)

2075 / C# / Шаблони / Фабричний метод (Factory Method)

 

Визначає загальний інтерфейс для створення об’єктів у батьківському класі, дозволяючи підкласам змінювати тип створюваних об’єктів

 

public interface IFactory
{
  void Drive(int km);
}

public class Scooter : IFactory
{
  public void Drive(int km)
  {
    Console.WriteLine("Drive the Scooter: " + km + " km");
  }
}

public class Bike : IFactory
{
  public void Drive(int km)
  {
    Console.WriteLine("Drive the Bike: " + km + " km");
  }
}

public abstract class VehicleFactory
{
  public abstract IFactory GetVehicle(string vehicle);
}

public class ConcreteVehicleFactory : VehicleFactory
{
  public override IFactory GetVehicle(string vehicle)
  {
    switch (vehicle)
    {
      case "Scooter":
        return new Scooter();
      case "Bike":
        return new Bike();
      default:
        throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", vehicle));
    }
  }
}

class Program
{
  static void Main(string[] args)
  {
    VehicleFactory factory = new ConcreteVehicleFactory();

    IFactory scooter = factory.GetVehicle("Scooter");
    scooter.Drive(25);

    IFactory bike = factory.GetVehicle("Bike");
    bike.Drive(10);

    Console.ReadKey();
  }
}

Drive the Scooter: 25 km
Drive the Bike: 10 km