130
votes

Most of the definition says:

An abstract factory provides an interface for creating families of related objects without specifying their concrete classes

What is the use of Abstract Factory Pattern as we can achieve the task via creating object of concrete class itself. Why do we have a factory method that creates object of Concrete class?

Please provide me any real life example where I must implement abstractFactory pattern?

15

15 Answers

27
votes

A real life example for the use of the Abstract Factory pattern is providing data access to two different data sources. Assume your application supports different data stores. (e.g. a SQL Database and an XML file). You have two different data access interfaces e.g. an IReadableStoreand IWritableStore defining the common methods expected by your application regardless of the type of data source used.

Which type of data source shall be used shouldn't change the way client code retrieves it's data access classes. Your AbstractDataAccessFactory knows which type of data source is configured and provides a concrete Factory for the client code, i.e. SqlDataAccessFactory or XmlDataAccessFactory. These concrete factories can create the concrete implementations, e.g. SqlReadableStore and SqlWriteableStore.

The DbProviderFactory in .NET Framework is an example of this pattern.

5
votes

If I understand you right - the question is, why do we have both the Factory method and the abstract factory patterns. You need abstract factory when different polymorphic classes has different instantiation procedure. And you want some module to create instances and use them, without knowing any details of object initialization. For example - you want to create Java objects doing some calculations. But some of them are part of the application, while other's bytecode should be read from the DB. In the other hand - why do we need factory method? Agree, that abstract factory overlaps it. But in some cases - it is much less code to write, having less classes and interfaces makes system easier to comprehend.

4
votes

Abstract Factories are great for supporting multiple platforms while keeping your code-base unified. Suppose you have a large Qt or GTK+ or .NET/Mono program that you want to run on Windows, Linux, and OSX. But you have a feature that is implemented in a different way on each platform (perhaps via the kernel32 API or a POSIX feature).

public abstract class Feature
{
    public abstract int PlatformSpecificValue { get; }

    public static Feature PlatformFeature
    {
        get
        {
            string platform;
            // do platform detection here
            if (platform == "Win32")
                return new Win32Feature();
            if (platform == "POSIX")
                return new POSIXFeature();
        }
    }

    // platform overrides omitted
}

With this Abstract Factory, your UI doesn't need to know anything about the current platform.

Feature feature = Feature.PlatformFeature;
Console.WriteLine(feature.PlatformSpecificValue);
4
votes

What is the use of Abstract Factory Pattern as we can achieve the task via creating object of concrete class itself. Why do we have a factory method that creates object of Concrete class?

In absence of Abstract Factory, Client needs to know details of concrete classes. This tight coupling has been removed with the Abstract Factory.

Now Factory Method exposes a contract, that client has to use. You can add more products to your factory by adding new products, which implement interface exposed by Factory Method.

Refer to these related SE questions for better understanding:

What is the basic difference between the Factory and Abstract Factory Patterns?

Intent:

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

You can understand Intent, Structure, Checklist and Rules of thumb of Abstract Factory pattern from this sourcemaking article.

Checklist:

  1. Decide if platform independence and creation services are the current source of pain.
  2. Map out a matrix of platforms versus products.
  3. Define a factory interface that consists of a factory method per product.
  4. Define a factory derived class for each platform that encapsulates all references to the new operator.
  5. The client should retire all references to new, and use the factory methods to create the product objects.
1
votes

If you look at the design patterns, almost all of them can be made redundant. But what pattern means a commonly used approach for a solution to a similar type of problems. A design pattern provides you a design level approach or solution to a set of similar type of design problem. Using design pattern help you solve your problem and hence deliver faster.

1
votes

it easy, imaging that you have a code that works with the abstraction, you should create abstractions and not concrete classes.

You should always work against abstractions because you can modify the code better.

This is a good example: http://en.wikipedia.org/wiki/Abstract_factory_pattern#C.23

1
votes

I find the Abstract Factory pattern overrated.

First of all, it doesn't happen that often that you have a set of interrelated types you want to instantiate.

Secondly, the level of indirection (abstraction) provided by interfaces normally suffices when working with dependency injection.

The typical example of WindowsGui vs MacGui vs ... where you'd have a WindowsButton, MacButton, WindowsScrollBar, MacScrollbar, etc. is often easier to implement by defining concrete Buttons, Scrollbars, etc. using Visitor and/or Interpreter pattern to provide actual behaviour.

1
votes

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.

Understanding and Implementing Abstract Factory Pattern in C#

1
votes

I think there is a place for abstract factory pattern rather than simple factory pattern in places where your instantiations are very complicated, too complicated and ugly for a single factory and too complicated for the UI to comprehends..

Let’s say this is a TYPE_A brand not a single class.. let’s say there is a family of 100 kind of similar classes of Type-A and you need to instantiate one object from them. Imagine there is a detail sophisticated info needed in order to make the correct object out of a brand of many similar type of objects, and in this object entity you need to know exactly which parameters to tune and how to tune them.

In the special factory for this brand we will have them differentiate and get the exact object to instantiate and also how to instantiate it . we will know that according to input from the net (let’s say what color is available in the online store) , and from other applications and services running in background (parameters the UI is not aware of them).

And maybe tomorrow we will have another family of let’s say type_B and type_C to instantiate. So the UI will have the “if else” to know if the user want a “type_A”, “type_B” or “type_C” – but the factories classes will decide exactly which class from the type (from the family) to build, and how to tune it – what values to set to its parameters , or to send to its contractor. All of this - according to many parameters that the UI is not aware of. All of this will be too much for a single factory class.

1
votes

Real life example is provided in System.Data.Common namespace that has abstract base classes which include DbConnection, DbCommand, and DbDataAdapter and are shared by the .NET Framework data providers, such as System.Data.SqlClient and System.Data.OracleClient which enable a developer to write generic data access code that does not depend on a specific data provider.

DbProviderFactories class provides static methods for creating a DbProviderFactory instance. The instance then returns a correct strongly typed object based on provider information and the connection string supplied at run time.

Example:

 DataTable allProvidersTable = DbProviderFactories.GetFactoryClasses();

enter image description here

        /* Getting SqlClient family members */
        DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
        DbCommand dbCommand = dbProviderFactory.CreateCommand();
        DbConnection dbConnection = dbProviderFactory.CreateConnection();
        DbDataAdapter dbDataAdapter = dbProviderFactory.CreateDataAdapter();

        SqlClientFactory sqlClientFactory = (SqlClientFactory)dbProviderFactory;
        SqlConnection sqlConnection = (SqlConnection)dbConnection;
        SqlCommand sqlCommand = (SqlCommand) dbCommand;
        SqlDataAdapter sqlDataAdapter = (SqlDataAdapter) dbDataAdapter;

        /* Getting OracleClient family members*/
        dbProviderFactory = DbProviderFactories.GetFactory("System.Data.OracleClient");
        dbCommand = dbProviderFactory.CreateCommand();
        dbConnection = dbProviderFactory.CreateConnection();
        dbDataAdapter = dbProviderFactory.CreateDataAdapter();

        OracleClientFactory oracleClientFactory = (OracleClientFactory)dbProviderFactory;
        OracleConnection oracleConnection = (OracleConnection)dbConnection;
        OracleCommand oracleCommand = (OracleCommand)dbCommand;
        OracleDataAdapter oracleDataAdapter = (OracleDataAdapter)dbDataAdapter;

Example-2 enter image description here

Code Solution architecture enter image description here

Concrete factory instances are provided using static Factory method as below

public  class FurnitureProviderFactory
{
    public static IFurnitureFactory GetFactory(string furnitureType)
    {
        if (furnitureType == "Wood")
        {
            return new WoodenFurnitureFactory();
        }
        if (furnitureType == "Plastic")
        {
            return new PlasticFurnitureFactory();
        }
        throw new Exception("Undefined Furniture");
    }
}
1
votes

Abstract factory or any factory for that matter, they exist to solve the same problem, i.e, "Abstraction of object creation".

It usually abstracts the following:

  1. if condition to decide which object to instantiate.
  2. new operator, instantiation of an object.

The responsibility of a factory is just that in a nutshell.

You can go through this for a detailed explanation.

0
votes

To answer directly your question, you can probably get away without using such a design pattern.

However bear in mind, that most of projects in the real-world evolve and you want to provide some kind of extensibility in order to make your project future-proof.

From my own experience, most of the time, a Factory is implemented and as the project grows it gets changed into more complex design patterns such as an Abstract Factory.

0
votes

It's all about dependencies. If you don't care about tight coupling and dependencies, then you don't need an abstract factory. But it will matter as soon as you write an application which needs maintenance.

0
votes

Say you create a.jar, and someone else uses your jar and wants to use a new concrete object in your code. If you are not using abstract factory, then she has to modify your code or overwrite your code. But if you are using abstract factory, then she can provide a factory and pass to your code and everything is fine.

Refined version: Consider the bellow scenario: Someone else wrote a framework. The framework uses an abstract factory and some concrete factories to create lots of objects at run time. So you can easily register your own factory to the existing framework and create your own objects. The framework is closed to modifications and still easy to extend because of abstract factory pattern.