Click here to Skip to main content
15,879,096 members
Articles / Programming Languages / C#
Article

Understanding and Implementing Abstract Factory Pattern in C#

Rate me:
Please Sign up or sign in to vote.
4.77/5 (67 votes)
10 Feb 2012CPOL3 min read 224.2K   2.7K   59   32
This article aims at understanding and Implementing Abstract Factory Pattern in C#.

Introduction

This article aims at understanding and implementing Abstract Factory Pattern in C#.

Background

Abstract factory pattern in useful when the client needs to create objects which are somehow related. If we need to create the family of related or dependent objects, then we can use Abstract Factory Pattern.

This pattern is particularly useful when the client doesn't know exactly what type to create. As an example, let's say a Showroom exclusively selling cellphones gets a query for the smart phones made by Samsung. Here we don't know the exact type of object to be created (assuming all the information for a phone is wrapped in the form of a concrete object). But we do know that we are looking for smart phones that are manufactured by Samsung. This information can actually be utilized if our design has Abstract factory implementation.

So with this idea of Abstract Factory pattern, we will now try to create a design that will facilitate the creation of related objects. We will go ahead and write a rudimentary application for the scenario we just talked about.

Using the Code

Let us start with the GOFs representation of Abstract Factory Pattern:

abstract factory uml

Let's see what each class does here:

  • AbstractFactory: declares an interface for operations that create abstract products
  • ConcreteFactory: implements the operations to create concrete product objects
  • AbstractProduct: declares an interface for a type of product object
  • Product: defines a product object to be created by the corresponding concrete factory implements the AbstractProduct interface
  • Client: uses interfaces declared by AbstractFactory and AbstractProduct classes

Now let us focus on the problem at hand. We need to create the appropriate object containing the information about cell phone based on the user request of 1. Type of phone 2. Phone manufacturer. For the sake of simplicity, let's assume we have 3 manufacturers:

  1. Nokia
  2. Samsung
  3. HTC

and there could be two types of phones:

  1. Smart Phones
  2. Dumb Phones

So with this information, we can safely say that we need three concrete factories (one for each manufacturer) and two sets of related products (one for smart and one for dumb).

Creating the Abstract Products

In our case, we need two abstract products ISmart and IDumb.

C#
interface IDumb
{
    string Name();
}
interface ISmart
{
    string Name();
}

Creating the Concrete Products

Now let us go ahead and create some concrete products for IDumb:

C#
class Asha : IDumb
{
    public string Name()
    {
        return "Asha";
    }
}

class Primo : IDumb
{
    public string Name()
    {
        return "Guru";
    }
}

class Genie : IDumb
{
    public string Name()
    {
        return "Genie";
    }
}

Let's do the same for ISmart:

C#
class Lumia : ISmart
{
    public string Name()
    {
        return "Lumia";
    }
}

class GalaxyS2 : ISmart
{
    public string Name()
    {
        return "GalaxyS2";
    }
}

class Titan : ISmart
{
    public string Name()
    {
        return "Titan";
    }
}

So we have all the concrete classes ready for all the Dumb Phones and smart phones irrespective of their manufacturers.

Creating the Abstract Factory

Now the way we associate these Concrete products with their manufacturers is using the Concrete factories. But before having the concrete factories, we need to have an Abstract Factory.

C#
interface IPhoneFactory //'I' stands for interface no relation with Iphone
{
    ISmart GetSmart();
    IDumb GetDumb();
}

Creating the Concrete Factories

Now we can create our Concrete Factories for each manufacturer:

C#
class SamsungFactory : IPhoneFactory
{
    public ISmart GetSmart()
    {
        return new GalaxyS2();
    }

    public IDumb GetDumb()
    {
        return new Primo();
    }
}

class HTCFactory : IPhoneFactory
{
    public ISmart GetSmart()
    {
        return new Titan();
    }

    public IDumb GetDumb()
    {
        return new Genie();
    }
}

class NokiaFactory : IPhoneFactory
{
    public ISmart GetSmart()
    {
        return new Lumia();
    }

    public IDumb GetDumb()
    {
        return new Asha();
    }
}

Creating the Client

Now we have all the Abstract product classes ready, all the Concrete Product classes ready. Our Abstract Factory is ready and all the Concrete Factories are ready. Now we can write client that will use this hierarchy of related products to create the products.

C#
enum MANUFACTURERS
{
    SAMSUNG,
    HTC,
    NOKIA
}
class PhoneTypeChecker
{
    ISmart sam;
    IDumb htc;
    IPhoneFactory factory;
    MANUFACTURERS manu;

    public PhoneTypeChecker(MANUFACTURERS m)
    {
        manu = m;
    }

    public void CheckProducts()
    {
        switch (manu)
        {
            case MANUFACTURERS.SAMSUNG:
                factory = new SamsungFactory();
                break;
            case MANUFACTURERS.HTC:
                factory = new HTCFactory();
                break;
            case MANUFACTURERS.NOKIA:
                factory = new NokiaFactory();
                break;
        }

        Console.WriteLine(manu.ToString() + ":\nSmart Phone: " + 
        factory.GetSmart().Name() + "\nDumb Phone: " + factory.GetDumb().Name());
    }
}

static void Main(string[] args)
{
    PhoneTypeChecker checker = new PhoneTypeChecker(MANUFACTURERS.SAMSUNG);

    checker.CheckProducts();

    Console.ReadLine();

    checker = new PhoneTypeChecker(MANUFACTURERS.HTC);

    checker.CheckProducts();
    Console.ReadLine();

    checker = new PhoneTypeChecker(MANUFACTURERS.NOKIA);

    checker.CheckProducts();
    Console.Read();
}

Now we can say we have a basic skeleton for the Abstract factory pattern ready. The concrete products here are not telling anything but names of products but they can contain more information too. Before we end the show, we can have a class diagram for the classes we created so that we can use this to map it with the GOFs diagram.

my abstract factory uml

Note: Please refer to the source code for implementation. Stepping through the code will really help in understanding this concept better.

Points of Interest

Abstract factory pattern in very useful in GUI based applications where we need to create related GUI components. My example here is solely for the purpose of understanding and there is no way the "Cell-phone-information-system" be designed this way (otherwise we will end up adding new classes every week). Please do let me know if I missed something. Perhaps for the experienced guys this article is not very useful but it could really be useful for beginners.

History

  • 10 Feb, 2012: Rudimentary Implementation of Abstract Factory Pattern in C#

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
QuestionWhat if i want to return all samsung products from factory. Pin
Member 132935451-Jan-18 20:39
Member 132935451-Jan-18 20:39 
SuggestionGood article, each parts of implementation explained clearly Pin
Murad Garibzada5-Apr-17 19:58
Murad Garibzada5-Apr-17 19:58 
Generalcomment Pin
Member 1280526920-Oct-16 5:27
Member 1280526920-Oct-16 5:27 
GeneralMy vote of 3 Pin
Member 1129793914-Feb-16 7:47
Member 1129793914-Feb-16 7:47 
GeneralRe: My vote of 3 Pin
super-e-11-Mar-20 23:39
super-e-11-Mar-20 23:39 
GeneralMy vote of 5 Pin
Roshan Kumar26-Nov-15 9:26
Roshan Kumar26-Nov-15 9:26 
Questiongood article Pin
safiyap3-Aug-15 6:06
safiyap3-Aug-15 6:06 
QuestionLol Pin
vrnithinkuamr7-Jun-15 21:23
vrnithinkuamr7-Jun-15 21:23 
QuestionDoubt in Abstract Factory Pattern Pin
jeyaraman1239-Dec-14 0:38
jeyaraman1239-Dec-14 0:38 
AnswerRe: Doubt in Abstract Factory Pattern Pin
Li Chen (George)28-Mar-15 2:29
Li Chen (George)28-Mar-15 2:29 
Question5 star for nice article Pin
pmq1231-Jul-14 5:28
pmq1231-Jul-14 5:28 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun19-May-14 22:26
Humayun Kabir Mamun19-May-14 22:26 
GeneralSimply awesome ! Pin
Octavio Tobar A19-May-14 6:06
Octavio Tobar A19-May-14 6:06 
GeneralMy vote of 5 Pin
Sachin Saklecha26-Mar-14 0:06
Sachin Saklecha26-Mar-14 0:06 
GeneralMy vote of 4 Pin
Jobless Creature6-Mar-14 14:54
professionalJobless Creature6-Mar-14 14:54 
QuestionNice article.... Really understood in one go.. Pin
Vinay Sakpal28-Feb-14 1:04
professionalVinay Sakpal28-Feb-14 1:04 
GeneralGood.. Pin
Member 1010866712-Feb-14 23:12
Member 1010866712-Feb-14 23:12 
QuestionVery well written Pin
BI Road Warrior29-Jan-14 2:48
BI Road Warrior29-Jan-14 2:48 
QuestionExcellent Pin
Member 1052676415-Jan-14 15:00
Member 1052676415-Jan-14 15:00 
QuestionGood Pin
Sudheendra Rao Bilamkar25-Dec-13 18:32
Sudheendra Rao Bilamkar25-Dec-13 18:32 
GeneralMy vote of 4 Pin
hoang214025-Aug-13 20:40
hoang214025-Aug-13 20:40 
GeneralMy vote of 5 Pin
Ming Xin1-Jul-13 4:56
professionalMing Xin1-Jul-13 4:56 
GeneralMy vote of 3 Pin
Good_shepherd23-Mar-13 8:11
Good_shepherd23-Mar-13 8:11 
GeneralMy vote of 5 Pin
PC8327-Feb-13 1:51
PC8327-Feb-13 1:51 
GeneralGood Article 5 Pin
Tanyaa25-Feb-13 20:10
Tanyaa25-Feb-13 20:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.