Quantcast
Channel: What are the differences between Abstract Factory and Factory design patterns? - Stack Overflow
Viewing all articles
Browse latest Browse all 23

Answer by Tom Dalling for What are the differences between Abstract Factory and Factory design patterns?

$
0
0

The Difference Between The Two

The main difference between a "factory method" and an "abstract factory" is that the factory method is a method, and an abstract factory is an object. I think a lot of people get these two terms confused, and start using them interchangeably. I remember that I had a hard time finding exactly what the difference was when I learnt them.

Because the factory method is just a method, it can be overridden in a subclass, hence the second half of your quote:

... the Factory Method pattern usesinheritance and relies on a subclassto handle the desired objectinstantiation.

The quote assumes that an object is calling its own factory method here. Therefore the only thing that could change the return value would be a subclass.

The abstract factory is an object that has multiple factory methods on it. Looking at the first half of your quote:

... with the Abstract Factory pattern, a classdelegates the responsibility of objectinstantiation to another object viacomposition ...

What they're saying is that there is an object A, who wants to make a Foo object. Instead of making the Foo object itself (e.g., with a factory method), it's going to get a different object (the abstract factory) to create the Foo object.

Code Examples

To show you the difference, here is a factory method in use:

class A {    public void doSomething() {        Foo f = makeFoo();        f.whatever();       }    protected Foo makeFoo() {        return new RegularFoo();    }}class B extends A {    protected Foo makeFoo() {        //subclass is overriding the factory method         //to return something different        return new SpecialFoo();    }}

And here is an abstract factory in use:

class A {    private Factory factory;    public A(Factory factory) {        this.factory = factory;    }    public void doSomething() {        //The concrete class of "f" depends on the concrete class        //of the factory passed into the constructor. If you provide a        //different factory, you get a different Foo object.        Foo f = factory.makeFoo();        f.whatever();    }}interface Factory {    Foo makeFoo();    Bar makeBar();    Aycufcn makeAmbiguousYetCommonlyUsedFakeClassName();}//need to make concrete factories that implement the "Factory" interface here

Viewing all articles
Browse latest Browse all 23

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>