create a factory method based on car in csharp

main.cs
using System;

// Base interface for cars
public interface ICar
{
    void Drive();
}

// Concrete class implementing the ICar interface
public class Sedan : ICar
{
    public void Drive()
    {
        Console.WriteLine("Driving a Sedan");
    }
}

// Concrete class implementing the ICar interface
public class Suv : ICar
{
    public void Drive()
    {
        Console.WriteLine("Driving an SUV");
    }
}

// Factory class to create different types of cars
public static class CarFactory
{
    public static ICar GetCar(string carType)
    {
        switch (carType.ToLower())
        {
            case "sedan":
                return new Sedan();
            case "suv":
                return new Suv();
            default:
                throw new ArgumentException("Invalid car type");
        }
    }
}

// Client code
class Program
{
    static void Main()
    {
        ICar myCar = CarFactory.GetCar("sedan");
        myCar.Drive();
        
        ICar anotherCar = CarFactory.GetCar("suv");
        anotherCar.Drive();
    }
}
1045 chars
56 lines

This code defines a factory method CarFactory that creates instances of different types of cars based on the input car type. The CarFactory class has a static method GetCar which takes a car type as input and returns an instance of the corresponding car. There are two concrete classes Sedan and Suv that implement the ICar interface. The client code demonstrates how to use the factory method to create and drive different types of cars.

gistlibby LogSnag