views:

76

answers:

2

Hello All,

It's regarding Abstract Factory pattern.

As we know that there are 2 ways we can use i.e.

  1. Either create the instance of concrete class directly or
  2. Provide an interface by which we can access concrete class

Can someone tell the advantage/dis-advantages that if I use option 1 then these are issues that can occur or vice-versa with real time example if possible.

Thanks in advance...

A: 

Directly creating objects certainly is easy (examples in C#):

public class Consumer()
{
    public void DoStuff()
    {
        var f = new Foo()
        f.DoIt("bar");
    }
}

While easy, it leads to tight coupling because you cannot vary the instance independently from the consumer.

While being more complex, a consumer using an Abstract Factory is loosely coupled:

public class Consumer()
{
    private readonly IFooFactory fooFactory;

    public Consumer(IFooFactory fooFactory)
    {
        if (fooFactory == null)
        {
            throw new ArgumentNullException("fooFactory");
        }

        this.fooFactory = fooFactory;
    }

    public void DoStuff()
    {
        var f = this.fooFactory.Create();
        f.DoIt("bar");
    }
}

This looks insanely more complex than the first version, but now you can vary the implementation of f independently of Consumer.

Not only will you be able to change the implementation, but you can also reuse or share instances between different consumers.

In many cases you don't need an Abstract Factory to enable loose coupling. Often, you can just inject dependencies directly into consumers instead of resorting to that extra level of indirection.

Mark Seemann
A: 

If you have a concrete class, which is not subclassed, and you are confident that it will never be, then you can just instantiate it as in your option 1 - for this there is no need for a factory.

If you have an interface / abstract class with several concrete subclasses, and you want to be able to vary the implementations without tying the client to any of them - this is when you use a factory (or dependency injection).

Péter Török