Why do we need Abstract factory design pattern?
Asked Answered
H

15

143

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?

Handbarrow answered 17/2, 2010 at 11:28 Comment(0)
L
230

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:

Leninakan answered 17/2, 2010 at 11:49 Comment(12)
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.Ulster
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.Ulster
@Ulster IIRC, the Factory Method pattern is a specialisation of the 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"?Leninakan
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.Ulster
@Ulster What does "a family of related products" mean in a C#/Java context, if not an interface or abstract base class?Leninakan
It means multiple, related interfaces or abstract base classes.Ulster
@Ulster Can you provide an example?Leninakan
Here is an example oodesign.com/abstract-factory-pattern.html. This is what the abstract factory pattern was originally created for.Tonnie
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 #38411399Tonnie
@Ulster 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, but as I wrote, I'm currently far away from my GoF copy.Leninakan
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 @Tonnie has correct examples, as does sourcemaking.Ulster
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 #4210291.Ulster
P
30

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.

Pattipattie answered 17/2, 2010 at 11:50 Comment(2)
This answer could accurately describe the Factory Method pattern, or Static Factory pattern, but not the Abstract Factory pattern.Ulster
Maybe this is a bit too late, but could you explain a bit further why this example does not fit the abstract factory method?Omniscient
T
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.

Trampoline answered 17/2, 2010 at 11:49 Comment(0)
H
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.
Hyetal answered 14/6, 2016 at 16:59 Comment(0)
N
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);
Nonmoral answered 17/7, 2013 at 15:33 Comment(1)
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?Celandine
T
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

Thornie answered 17/2, 2010 at 11:51 Comment(0)
H
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.

Harkness answered 28/8, 2020 at 3:33 Comment(0)
O
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.

Overrate answered 17/2, 2010 at 11:40 Comment(0)
T
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.

Tips answered 17/2, 2010 at 12:21 Comment(2)
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.Glandular
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.Adown
M
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.

Merideth answered 17/2, 2010 at 13:47 Comment(0)
L
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#

Lelea answered 13/10, 2017 at 16:3 Comment(0)
S
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.

Shelbyshelden answered 3/12, 2017 at 16:57 Comment(0)
E
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.

Elytron answered 4/3, 2015 at 7:5 Comment(0)
C
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.

Congou answered 17/11, 2015 at 6:34 Comment(0)
I
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.

Imaginary answered 30/3, 2023 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.