Click here to Skip to main content
11,642,216 members (60,001 online)
Click here to Skip to main content

Tagged as

Understanding and Implementing Abstract Factory Pattern in C#

, 10 Feb 2012 CPOL 89.2K 1.7K 45
Rate this:
Please Sign up or sign in to vote.
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.

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

Creating the Concrete Products

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

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:

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.

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:

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.

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)

Share

About the Author

Rahul Rajat Singh
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

You may also be interested in...

Comments and Discussions

 
QuestionLol Pin
vrnithinkuamr7-Jun-15 21:23
membervrnithinkuamr7-Jun-15 21:23 
QuestionDoubt in Abstract Factory Pattern Pin
jeyaraman1239-Dec-14 0:38
memberjeyaraman1239-Dec-14 0:38 
AnswerRe: Doubt in Abstract Factory Pattern Pin
Li Chen (George)28-Mar-15 2:29
memberLi Chen (George)28-Mar-15 2:29 
Question5 star for nice article Pin
pmq1231-Jul-14 5:28
memberpmq1231-Jul-14 5:28 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun19-May-14 22:26
memberHumayun Kabir Mamun19-May-14 22:26 
GeneralSimply awesome ! Pin
Octavio Tobar A19-May-14 6:06
memberOctavio Tobar A19-May-14 6:06 
GeneralMy vote of 5 Pin
Sachin Saklecha26-Mar-14 0:06
memberSachin Saklecha26-Mar-14 0:06 
GeneralMy vote of 4 Pin
Jobless Creature6-Mar-14 14:54
memberJobless Creature6-Mar-14 14:54 
QuestionNice article.... Really understood in one go.. Pin
Vinay Sakpal28-Feb-14 1:04
memberVinay Sakpal28-Feb-14 1:04 
GeneralGood.. Pin
Member 1010866712-Feb-14 23:12
memberMember 1010866712-Feb-14 23:12 
QuestionVery well written Pin
Member 1011881429-Jan-14 2:48
memberMember 1011881429-Jan-14 2:48 
QuestionExcellent Pin
Member 1052676415-Jan-14 15:00
memberMember 1052676415-Jan-14 15:00 
QuestionGood Pin
Sudheendra Rao Bilamkar25-Dec-13 18:32
memberSudheendra Rao Bilamkar25-Dec-13 18:32 
GeneralMy vote of 4 Pin
hoang214025-Aug-13 20:40
memberhoang214025-Aug-13 20:40 
GeneralMy vote of 5 Pin
soujiro seta1-Jul-13 4:56
membersoujiro seta1-Jul-13 4:56 
GeneralMy vote of 3 Pin
Good_shepherd23-Mar-13 8:11
memberGood_shepherd23-Mar-13 8:11 
GeneralMy vote of 5 Pin
PC8327-Feb-13 1:51
memberPC8327-Feb-13 1:51 
GeneralGood Article 5 Pin
Tanyaa25-Feb-13 20:10
memberTanyaa25-Feb-13 20:10 
GeneralMy vote of 5 Pin
Md. Humayun Rashed21-Feb-13 23:12
memberMd. Humayun Rashed21-Feb-13 23:12 
GeneralMy vote of 5 Pin
helloBug19-Feb-13 12:17
memberhelloBug19-Feb-13 12:17 
GeneralMy Vote 5 Pin
manoharmind2-Oct-12 23:49
membermanoharmind2-Oct-12 23:49 
Question6 Pin
pune15-Jun-12 2:45
memberpune15-Jun-12 2:45 
GeneralThanks Pin
pakirikus14-Apr-12 20:08
memberpakirikus14-Apr-12 20:08 
GeneralMy vote of 4 Pin
quentininsa10-Feb-12 20:50
memberquentininsa10-Feb-12 20:50 
GeneralMy vote of 4 Pin
pietvredeveld10-Feb-12 5:19
memberpietvredeveld10-Feb-12 5:19 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 10 Feb 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid