Abstract Factory model for car building, abstract factory for car building
Abstract Factory models can be used to build vehicles.
There are many brands of cars, and there are also many attributes of the car, such as the type, displacement, number of doors, and so on. An abstract class related to vehicles 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, an interface for car creation is extracted:
public interface ICarFactory
{
Car ProduceCar();
}
Write a Car derived class:
public class MyCar : Car
{
public MyCar()
{
Model = "Model 001 ";
Engine = "Engine V ";
Transmission = "displacement 1 ";
Body = "SUV";
Doors = 4;
Accessores. Add ("Interior ");
Accessores. Add ("Exterior Decoration ");
}
public override void ShowCarInfo()
{
Console.WriteLine(Model);
Console.WriteLine(Engine);
Console.WriteLine(Body);
Console. WriteLine ("number of Doors:" + Doors );
Console. WriteLine ("includes :");
foreach (var accessory in Accessores)
{
Console.WriteLine("\t{0}", accessory);
}
}
}
MyCar requires a specific factory to build a car. 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, you can find a specific factory.
static void Main(string[] args)
{
ICarFactory carFactory = new MyFactory();
carFactory.ProduceCar().ShowCarInfo();
Console.ReadKey();
}
Summary:
1. abstract classes for factory production objects and derived classes
2. An abstract factory interface is required.
3. To build a car in an abstract factory, all the details must be designed in the abstract class that represents the car. The scalability is poor.