Factory Pattern and Abstract Factory design pattern

We already know that factory and abstract factory designing patterns both are creational design pattern, but there are some difference, let’s understand those differences with code example.

abstract factory designing pattern

Factory Design Pattern

Here we define a car factory interface, which will contain all mandatory methods for defining any different type of car, for example Maruti, Honda etc.

public interface ICarFactory
{
    void Drive(int miles);
}

Now let’s define Maruti car class, with implementation of method from ICarFactory interface.

public class Maruti : ICarFactory
{
    public void Drive(int miles)
    {
        Console.WriteLine("Maruti : " + miles.ToString() + "km");
    }
}
Abstract Factory Pattern

Here we define two different type of car, and all the car brand will consume these interface to create their car type.

interface IElectricCar
{
    string GetCarDetails();
}
interface IPetrolCar
{
    string GetCarDetails();
}    

Any car brand we create, we must inherit from the interface below.

    
interface ICar
{
    IElectricCar GetElectricCar();
    IPetrolCar GetPetrolCar();
}

So far from factory and abstract factory implementation you can see the difference, that abstract factory contain abstract definition of factory design.

Factory Pattern...

Create a abstract class CarFactory, Which will return abstract IFactory type method; you can have any number of methods as per your requirement.

public abstract class CarFactory
{
    public abstract ICarFactory GetCar(string car);
}

Now create a concrete class inherited from the CarFactory, where the actual implementation takes place

public class ConcreteCarFactory : CarFactory
{
    public override ICarFactory GetCar(string car)
    {
        switch (car)
        {
            case "maruti":
                return new Maruti();
            case "honda":
                return new Honda();
            default:
                throw new ApplicationException(car + " cannot be created");
        }
    }
}
Abstract Factory ...

Now let's say we want to create cars for a brand called Maruti by using above abstract definition, se we create petrol car and electric car both.

class MarutiPetrol : IPetrolCar
{
    public string GetCarDetails()
    {
        return "Maruti petrol details";
    }
}

We have created two different type of car for the brand Maruti, MarutiPetrol and MarutiElectric.

class MarutiElectric : IElectricCar
{
    public string GetCarDetails()
    {
        return "Maruti electric details";
    }
}

Good to Read
You may also read
Data Analysis using Asp.net MVC
Data Analysis using Asp.net MVC
How to add facebook chat in website
add facebook chat in website
How to implement google search in website
implement google custom search