Click here to Skip to main content
Click here to Skip to main content

Tagged as

Understanding and Implementing Abstract Factory Pattern in C#

, 10 Feb 2012 CPOL
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
Software Developer (Senior)
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[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
Question5 star for nice article Pinmemberpmq1231-Jul-14 6:28 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun19-May-14 23:26 
GeneralSimply awesome ! PinmemberOctavio Tobar A19-May-14 7:06 
GeneralMy vote of 5 PinmemberSachin Saklecha26-Mar-14 1:06 
GeneralMy vote of 4 PinmemberJobless Creature6-Mar-14 15:54 
QuestionNice article.... Really understood in one go.. PinmemberVinay Sakpal28-Feb-14 2:04 
GeneralGood.. PinmemberMember 1010866713-Feb-14 0:12 
QuestionVery well written PinmemberMember 1011881429-Jan-14 3:48 
QuestionExcellent PinmemberMember 1052676415-Jan-14 16:00 
QuestionGood PinmemberSudheendra Rao Bilamkar25-Dec-13 19:32 
GeneralMy vote of 4 Pinmemberhoang214025-Aug-13 21:40 
GeneralMy vote of 5 Pinmembersoujiro seta1-Jul-13 5:56 
GeneralMy vote of 3 PinmemberGood_shepherd23-Mar-13 9:11 
GeneralMy vote of 5 PinmemberPC8327-Feb-13 2:51 
GeneralGood Article 5 PinmemberTanyaa25-Feb-13 21:10 
GeneralMy vote of 5 PinmemberMd. Humayun Rashed22-Feb-13 0:12 
GeneralMy vote of 5 PinmemberhelloBug19-Feb-13 13:17 
GeneralMy Vote 5 Pinmembermanoharmind3-Oct-12 0:49 
Question6 Pinmemberpune15-Jun-12 3:45 
GeneralThanks Pinmemberpakirikus14-Apr-12 21:08 
GeneralMy vote of 4 Pinmemberquentininsa10-Feb-12 21:50 
GeneralMy vote of 4 Pinmemberpietvredeveld10-Feb-12 6: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
Web02 | 2.8.1411023.1 | Last Updated 10 Feb 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid