Factory Design Pattern is one of Creational Pattern Patterns where client does not know which class serves its request. Factory method creates the object for specific class from available classes based on information supplied by the client.
Today let's discuss about the Factory Design Pattern with online shop example in C#. For example let's take Amazon as online shop which has several branches all over world and it delivers the goods based on user location. For example if it receives request from US it delivers the goods from US market or if the request is from UK it uses UK market. Here client is User, sub-classes are US-Market; UK-Market, Factory Method is the method which decides which sub-class has to call based on User location.
In Factory Design Pattern all sub-classes contains some methods with same name, so use one interface which contains common methods to implement. Please find below the main components of online shop example which uses the factory design pattern.
Interface: IShop
Sub-classes: US-Market, UK-Market
Factory Method: Deliver() which decides sub-class instantiation based on client input
Client: User who purchases goods
IShop.cs
namespace FactoryDesignPatternC
{
interface IShop
{
string DeliverItems();
}
}
US-Market.cs
namespace FactoryDesignPatternC
{
class US_Market : IShop
{
#region IShop Members
public string DeliverItems()
{
return "Items Delivers from US Market";
}
#endregion
}
}
UK-Market
namespace FactoryDesignPatternC
{
class UK_Market:IShop
{
#region IShop Members
public string DeliverItems()
{
return "Items Delivers from UK Market";
}
#endregion
}
}
Factory:
using System;
namespace FactoryDesignPatternC
{
class Factory
{
public string Purchase(string sLoc)
{
IShop objIShop;
if (sLoc == "US")
{
objIShop = new US_Market();
}
else if (sLoc == "UK")
{
objIShop = new UK_Market();
}
else
{
throw new NotImplementedException();
}
return objIShop.DeliverItems();
}
}
}
As shown above created the interface, sub-classes and Factory method which decides sub-class call. Now let's call the Factory method as shown below.
Client:
using System;
namespace FactoryDesignPatternC
{
class Program
{
static void Main(string[] args)
{
Factory obj = new Factory();
Console.WriteLine(obj.Purchase("US"));
Console.ReadLine();
}
}
}
As shown above client is calling only Factory method Purchase() by passing its location and Factory method Purchase() decides which sub-class has to call from available sub-classes based on client information.