140

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?

David Hall
  • 32,624
  • 10
  • 90
  • 127
Amit
  • 3,358
  • 9
  • 34
  • 48

15 Answers15

229

Abstract Factory is a very central design pattern for Dependency Injection (DI). Here's a list of Stack Overflow questions where application of Abstract Factory has been accepted as the solution.

To the best of my understanding, these questions represent real concerns or problems that people had, so that should get you started with some real-life examples:

Community
  • 1
  • 1
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 7
    All of these examples describe the Factory Method Pattern, because all of them return a single product interface. None of these is an Abstract Factory Pattern, because none of them produce a family of related product interfaces. – jaco0646 Jul 16 '16 at 14:15
  • 45
    In the interest of full disclosure, the author of this answer should have made it clear that he is also the author of every one of the linked answers; so this list is **NOT** a representative sample from the SO community. – jaco0646 Jul 16 '16 at 14:24
  • 1
    @jaco0646 IIRC, the [Factory Method pattern](https://en.wikipedia.org/wiki/Factory_method_pattern) is a specialisation of the [Template Method pattern](https://en.wikipedia.org/wiki/Template_method_pattern), which relies on inheritance. I may be mistaken, though, as I'm currently travelling, and don't have my GoF book with me. What do you mean by "none of them produce a family of related product interfaces"? – Mark Seemann Jul 16 '16 at 15:01
  • 1
    The simplest clue that indicates a factory does not conform to the Abstract Factory Pattern is to count the abstract products the factory produces (I used the term "product interfaces" in place of "abstract products" to avoid overuse of the word "abstract"). A factory that produces a single abstract product cannot be an Abstract Factory, because by definition, Abstract Factory produces a _family of related products_. It's critical to note this _family_ is not referring to different implementations of one interface, but rather to products with different, related interfaces. – jaco0646 Jul 17 '16 at 14:20
  • @jaco0646 What does "a family of related products" mean in a C#/Java context, if not an interface or abstract base class? – Mark Seemann Jul 17 '16 at 15:18
  • It means multiple, related interfaces or abstract base classes. – jaco0646 Jul 17 '16 at 23:30
  • @jaco0646 Can you provide an example? – Mark Seemann Jul 18 '16 at 07:28
  • 1
    Here is an example http://www.oodesign.com/abstract-factory-pattern.html. This is what the abstract factory pattern was originally created for. – user2802557 Jul 18 '16 at 16:17
  • I actually created a question asking what is the difference between what you describe as an abstract factory pattern and the other way which maybe you could help with http://stackoverflow.com/questions/38410899/are-these-both-the-abstract-factory-pattern – user2802557 Jul 18 '16 at 16:19
  • @jaco0646 So you're saying that it can only be an Abstract Factory if the factory defines more than a single method? That's not what the [Wikipedia article on the topic describes](https://en.wikipedia.org/wiki/Abstract_factory_pattern), but as I wrote, I'm currently far away from my GoF copy. – Mark Seemann Jul 18 '16 at 19:45
  • Yes, that's what I'm saying. Looking at the (current) content of the Wikipedia article, the introduction is correct: it consistently describes the creation of related products (plural). The first class diagram is incorrect, as is the corresponding C# example. Both are the Factory Method Pattern. The UML class diagram, however, is accurate. The oodesign link from @user2802557 has correct examples, as does [sourcemaking](https://sourcemaking.com/design_patterns/abstract_factory). – jaco0646 Jul 18 '16 at 20:47
  • I need to correct my first and last comments above where I made the common mistake of treating factory patterns as a dichotomy between Abstract Factory and Factory Method. While these examples are not Abstract Factories, neither are they Factory Methods. These examples are commonly called Simple Factories, a coding idiom outside the GoF. I've described all of these patterns in more detail at http://stackoverflow.com/questions/4209791/design-patterns-abstract-factory-vs-factory-method/38668246#38668246. – jaco0646 Mar 20 '17 at 13:51
28

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.

Johannes Rudolph
  • 35,298
  • 14
  • 114
  • 172
  • 20
    This answer could accurately describe the Factory Method pattern, or Static Factory pattern, but not the Abstract Factory pattern. – jaco0646 Jul 16 '16 at 13:32
5

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.

David Gruzman
  • 7,900
  • 1
  • 28
  • 30
4

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.
EnterTheCode
  • 474
  • 5
  • 20
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
3

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);
piedar
  • 2,599
  • 1
  • 25
  • 37
  • 3
    I don't get it, how is this different from just using factory methods to return a abstract type so that the client doesn't know the implementation details? – kiwicomb123 Oct 26 '18 at 10:33
2

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

Pablo Castilla
  • 2,723
  • 2
  • 28
  • 33
2

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.

Uday Reddy
  • 1,337
  • 3
  • 16
  • 38
1

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.

Kangkan
  • 15,267
  • 10
  • 70
  • 113
1

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.

eljenso
  • 16,789
  • 6
  • 57
  • 63
  • theres a specific purpose for it. with dependency injection you dont want service locators further down from the composite root. instead you use an injected abstract factory. – Adam Tuliper Oct 26 '11 at 14:44
  • 2
    well...using service locator with DI is an anti patteren. An Abstract Factory is the universal solution when we need to create DEPENDENCIES from runtime values. – TheMentor Jun 05 '13 at 21:11
1

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.

BlueTrin
  • 9,610
  • 12
  • 49
  • 78
1

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#

Amir Shabani
  • 690
  • 2
  • 14
  • 36
1

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.

Udi Reshef
  • 1,083
  • 1
  • 11
  • 14
0

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.

Daniel B
  • 4,145
  • 1
  • 21
  • 21
0

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.

Adrian Liu
  • 385
  • 3
  • 13
0

I asked this question at a company once and while it is a short answer, it held true for me.

Abstract Factory moves the level of abstraction up one level, so to speak, so the underlying implementations can be fairly easily swapped out with a different implementation.

In our case we used Abstract Factory above Hibernate, but we could have swapped Hibernate out with Toplink, iBatis, or something else because the abstract factory created an abstraction level above the Hibernate code.

James Drinkard
  • 15,342
  • 16
  • 114
  • 137