Introduction
This tip is about to implement the Abstract Factory Pattern in C#
Background
Design patterns are general reusable solutions to common problems that occurred in software designing. There are broadly 3 categories of design patterns, i.e., Creational, Behavioral and Structural.
Abstract factory pattern comes under the category of creational design patterns.
It basically provides a way/interface for creating groups of object or you can say families of object which are inter-dependent or of similar types. Also, for creating this families of objects, we do not requires the class name.
So Abstract factory defination say
"Provide an interface for creating families of related or dependent objects without specifying their concrete classes."
Source: Abstract Factory
Using the code
1. Consider the below code, here two interfaces having the one method each i.e. DisplayBase()
and DisplayTop()
interface INormal
{
string DisplayBase();
}
interface IAboveNormal
{
string DisplayTop();
}
2. Here are some concrete classes which are implementing the methods of above interfaces.
public class clsWagonR : INormal
{
public string DisplayBase()
{
return "WagonR";
}
}
public class clsSwift : IAboveNormal
{
public string DisplayTop()
{
return "Swift";
}
}
public class clsAudiA4 : INormal
{
public string DisplayBase()
{
return "Audi A4";
}
}
public class clsAudiQ7 : IAboveNormal
{
public string DisplayTop()
{
return "Audi Q7";
}
}
3. Now, We will create the abstract factory patter. In below code there is an interface which clubs the above interface i.e.
INormal
and
IAboveNormal
. Also see the classes which are implementing this interface.
interface Icar
{
INormal GetNormal();
IAboveNormal GetAboveNormal();
}
class clsMaruti : Icar
{
public INormal GetNormal()
{
return new clsWagonR();
}
public IAboveNormal GetAboveNormal()
{
return new clsSwift();
}
}
class clsAudi : Icar
{
public INormal GetNormal()
{
return new clsAudiA4();
}
public IAboveNormal GetAboveNormal()
{
return new clsAudiQ7();
}
}
4. Next, the class which you can see below contains the method which decides whose object should be now created (you can put this method in client code instead of making new class).
class clsDecider
{
public string GetCarDetails(int iCarType)
{
Icar ObjClient=null;
switch (iCarType)
{
case 1:
ObjClient = new clsMaruti();
break;
case 2:
ObjClient = new clsAudi();
break;
default:
ObjClient = new clsMaruti();
break;
}
string sOutput = "Normal Car is: "+ ObjClient.GetNormal().DisplayBase()+", Above Normal car is: "+ ObjClient.GetAboveNormal().DisplayTop();
return sOutput;
}
}
5. Finally, Below is my client code:
clsDecider ObjDecider = new clsDecider();
string sResult= ObjDecider.GetCarDetails(2);
In client code, I have harcoded 2, you can pass this value through some control like Textbox, Radiobutton or Dropdown.