The Abstract Factory pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.
This pattern is useful in situations where a system needs to be independent of how its products are created, composed and represented. The factory interface defines a set of methods that return different interfaces or classes, which represent different products. The concrete factories implement these interfaces and provide the actual objects.
The abstract factory pattern is often used when a system should be independent of the way the objects it creates are generated or it needs to work with multiple types of products.
For example, an application that needs to work with different types of UI widgets (e.g. Windows, Mac, and Web) could use an abstract factory to create the widgets for a specific platform. The application code would not need to know the specific classes for the widgets, only the abstract factory that produces them.
In C#, the Abstract Factory pattern can be implemented using interfaces and classes.
First, we define an interface that represents the factory, typically named IAbstractFactory
. This interface should define methods that return different types of products (e.g. ICar
and IBike
).
public interface IAbstractFactory
{
ICar CreateCar();
IBike CreateBike();
}
public interface ICar
{
string GetCarType();
}
public interface IBike
{
string GetBikeType();
}
Then, we create concrete classes that implement the factory and product interfaces.
public class LuxuryCarFactory : IAbstractFactory
{
public ICar CreateCar()
{
return new LuxuryCar();
}
public IBike CreateBike()
{
return new SportsBike();
}
}
public class LuxuryCar : ICar
{
public string GetCarType()
{
return "Luxury Car";
}
}
public class SportsBike : IBike
{
public string GetBikeType()
{
return "Sports Bike";
}
}
Finally, the client code can use the abstract factory to create objects, without needing to know the concrete classes of the products.
IAbstractFactory factory = new LuxuryCarFactory();
ICar car = factory.CreateCar();
IBike bike = factory.CreateBike();
Console.WriteLine(car.GetCarType());
Console.WriteLine(bike.GetBikeType());
This will print "Luxury Car" and "Sports Bike" respectively. This is just an example of how the Abstract Factory pattern can be implemented in C#. The pattern can also be implemented in various other ways and can be combined with other design patterns for more complex systems.