Basic difference between Abstract Factory and Factory?

7

I was taking a look at the PHP Manual and saw an example implementation of the Factory pattern.

Example:

class Exemplo
{
    // Método Factory parametrizado
    public static function factory($type)
    {
        if (include_once 'Drivers/' . $type . '.php') {
            $classname = 'Driver_' . $type;
            return new $classname;
        } else {
            throw new Exception ('Driver não encontrado');
        }
    }
}

Output:

// Carregar um driver MySQL
$mysql = Exemplo::factory('MySQL');

// Carregar um driver SQLite 
$sqlite = Exemplo::factory('SQLite');

In the PHP of the Right Way , I saw that through Factory , one class simply creates the object you would like to use .

I do not have any examples of Abstract Factory , but I have already seen a course I did. And that confused me.

I would like to know, in the simplest possible way, what are the differences between these two patterns.

    
asked by anonymous 10.09.2015 / 17:27

1 answer

8

The name of the pattern until it is quite significant.

Basically, Abstract is the technique of using a factory abstracting knowledge of the concrete implementation of that factory .

In the same way that a factory has the ability to abstract the concrete implementation of the type it delivers by returning an interface instead of returning a class, the abstract factory in> determines a factory interface abstracting the actual implementation of the factory that is returned to the factory consumer.

Pseudo-code example

Factory

Factory factory = new Factory();
IObjeto objeto = factory.create();

Abstract Factory

IFactory factory = abstractFactory.create();
IObjeto objeto = factory.create();

In these examples, IObject and IFactory are interface declarations, not type declarations. The type of object that is actually obtained in each of the examples is "unknown" or irrelevant to the consumer.

The concrete implementation of factory that will be obtained by using the pattern Abstract Factory will then depend on decisions external to the factory consumer code, and will be determined for example by configuration file, business rules observation, dependency injection, etc.

Remembering that I spoke in interface in the sense of a contract. Although interface declarations are a very common basic feature in languages that support object orientation, you do not necessarily have to use this kind of statement if you are not called by the language or if there is a cool way.

    
10.09.2015 / 18:01