SoFunction
Updated on 2025-03-01

C# builds cars through abstract factory model

You can use the abstract factory model to build cars.

There are many brands of cars, and there are many attributes of cars, such as the type of cars, displacement, number of doors, etc. An abstract class about cars can be extracted:

    public abstract class Car
    {
        public string Model { get; set; }
        public string Engine { get; set; }
        public string Transmission { get; set; }
        public string Body { get; set; }
        public int Doors { get; set; }
        public List<string> Accessores = new List<string>();
        public abstract void ShowCarInfo();
    }

Since it is an abstract factory, extract an interface for making cars:

    public interface ICarFactory
    {
        Car ProduceCar();
    }

Write a derived class of Car:

    public class MyCar : Car
    {
        public MyCar()
        {
            Model = "Model 001";
            Engine = "Engine V";
            Transmission = "Displacement 1";
            Body = "SUV";
            Doors = 4;
            ("Interior");
            ("Exterior decoration");
        }
        public override void ShowCarInfo()
        {
            (Model);
            (Engine);
            (Body);
            ("Number of Doors:" + Doors);
            ("include:");
            foreach (var accessory in Accessores)
            {
                ("\t{0}", accessory);
            }
        }
    }

MyCar needs a corresponding specific factory to build cars. Write a specific factory class to implement the ICarFactory interface.

    public class MyFactory : ICarFactory
    {
        public Car ProduceCar()
        {
            return new MyCar();
        }
    }

On the client, if you want to build a car, just look for a specific factory.

        static void Main(string[] args)
        {
            ICarFactory carFactory = new MyFactory();
            ().ShowCarInfo();
            ();
        }

Summarize:

1. Abstract classes and derived classes that require factory production objects
2. Require an abstract factory interface
3. Build cars through abstract factories, all details must be designed in the abstract category representing cars, which is not very extensible.

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links