Why do we need Abstract factory design pattern?

2019-01-01 13:54发布

问题:

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?

回答1:

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:

  • Is there a pattern for initializing objects created via a DI container
  • Can't combine Factory / DI
  • WCF Dependency injection and abstract factory
  • How to set up IoC when a key class needs Session (or other context-specific variable)
  • How to Resolve type based on end-user configuration value?
  • Strategy Pattern and Dependency Injection using Unity
  • Abstract factory pattern on top of IoC?
  • Is this the correct way to use and test a class that makes use of the factory pattern?
  • DDD Book, Eric Evans: Please explain what is meant by "The FACTORY should be abstracted to the type desired rather than the concrete class(es) created."
  • DI container, factory, or new for ephemeral objects?
  • How to unit test instance creation?
  • What is the best strategy for Dependency Injection of User Input?


回答2:

A real life example for the use of the Abstract Factory pattern is providing data access to two different data sources (e.g. a SQL Database and a XML file). You have two different data access classes (a gateway to the datastore). Both inherit from a base class that defines the common methods to be implemented (e.g. Load, Save, Delete).

Which data source shall be used shouldn\'t change the way client code retrieves it\'s data access class. Your Abstract Factory knows which data source shall be used and returns an appropriate instance on request. The factory returns this instance as the base class type.



回答3:

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:

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 need to know details of concrete classes. This tight coupling has been removed with Abstract Factory.

Now Factory Method exposes an 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.


回答5:

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);


回答6:

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.



回答7:

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



回答8:

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.



回答9:

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.



回答10:

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.



回答11:

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.



回答12:

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#



回答13:

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.