C# | Abstract Factory Pattern | Creational Design Pattern
Abstract Factory patterns act as a super-factory which creates other factories. This pattern is also called as Factory of factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.
UML Diagram
The classes, interfaces and objects in the above UML class diagram are as
follows:
1.
AbstractFactory
This is an interface which is used to create
abstract product
2.
ConcreteFactory
This is a class which implements the
AbstractFactory interface to create concrete products.
3.
AbstractProduct
This is an interface which declares a type of
product.
4.
ConcreteProduct
This is a class which implements the
AbstractProduct interface to create product.
5.
Client
This is a class which use AbstractFactory and AbstractProduct interfaces to create a family of related objects.
Code syntax -
public interface ICar
{
void manufacture();
}
public interface IBike
{
void manufacture();
}
public abstract class VehicleCompany
{
public abstract ICar GetCar();
public abstract IBike GetBike();
}
public class TeslaCompany : VehicleCompany
{
public override ICar GetCar()
{
return new TeslaCar();
}
public override IBike GetBike()
{
return new TeslaBike();
}
}
public class TataCompany : VehicleCompany
{
public override ICar GetCar()
{
return new TataCar();
}
public override IBike GetBike()
{
return new TataBike();
}
}
public class TataCar : ICar
{
public void manufacture()
{
throw new NotImplementedException();
}
}
public class TataBike : IBike
{
public void manufacture()
{
throw new NotImplementedException();
}
}
public class TeslaCar : ICar
{
public void manufacture()
{
throw new NotImplementedException();
}
}
public class TeslaBike : IBike
{
public void manufacture()
{
throw new NotImplementedException();
}
}
internal class Program
{
static void Main(string[] args)
{
VehicleCompany teslaComapny = new TeslaCompany();
IBike teslaBike = teslaComapny.GetBike();
ICar teslaCar = teslaComapny.GetCar();
VehicleCompany tataCompany = new TataCompany();
IBike tataBike = tataCompany.GetBike();
ICar tataCar =tataCompany.GetCar();
}
}
When to use it?
1. Create
a set of related objects, or dependent objects which must be used together.
2. System
should be configured to work with multiple families of products.
3. The
creation of objects should be independent from the utilizing system.
4. Concrete
classes should be decoupled from clients.
Comments
Post a Comment