Abstract Factory pattern is used for creating relational object groups which are defined as Interfaces.
The reason why we would need an Abstract Factory is its being used while creating object for the same Class Group.While hiding the other classes,we're achieving our goals here.If we're to work with lots of Class Groups at the same time,then it would be best if we've used Abstract Factory Design Pattern.
Each object is defined as an interface.Lets make a simple demo.In our simple demo we will use Car Types.
What kind of Car are there?
Sports,Mini...etc I think 2 of them are enough.
I will be using a .NET Console Project using C#. It doesnt matter which architecture you use.Design Patterns are archi-free can be applied in any languages that supports Interfaces and moreover OOP.
Assuming you've already created a new Console project in c#
1) Create a new Interface named "Car" that takes a string parameter.
public interface Car
{
string getCarType();
}
2) Create 2 Car Type Classes(SportsCar & MiniCar) that implements our Car Interface and returns string as result:
public class SportsCar : Car
{
public string getCarType()
{
return "A Sports Car!";
}
}
public class MiniCar : Car
{
public string getCarType()
{
return "A Mini Car!";
}
}
3) Create your AbstractFactory interface for implementing.
public interface AbstractFactory
{
Car getSportCars();
Car getMiniCars();
}
4) Finally implement this interface in your Program class using:
class Program : AbstractFactory
After implementation, the methods used inside this interface will be added automatically:
public Car getSportCars()
{
return new SportsCar();
}
public Car getMiniCars()
{
return new MiniCar();
}
5) And finally call your Cars inside a Main function:
static void Main(string[] args)
{
SportsCar car = new SportsCar();
Console.WriteLine(car.getCarType());
MiniCar car2 = new MiniCar();
Console.WriteLine(car2.getCarType());
Console.ReadLine();
}
And then run your project.You will see a similar output:

Full Source Code:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program : AbstractFactory
{
static void Main(string[] args)
{
SportsCar car = new SportsCar();
Console.WriteLine(car.getCarType());
MiniCar car2 = new MiniCar();
Console.WriteLine(car2.getCarType());
Console.ReadLine();
}
public Car getSportCars()
{
return new SportsCar();
}
public Car getMiniCars()
{
return new MiniCar();
}
}
public interface AbstractFactory
{
Car getSportCars();
Car getMiniCars();
}
public interface Car
{
string getCarType();
}
public class SportsCar : Car
{
public string getCarType()
{
return "A Sports Car!";
}
}
public class MiniCar : Car
{
public string getCarType()
{
return "A Mini Car!";
}
}
}