Dev
Dev

Reputation: 329

Builder vs Factory Method pattern

I was reading about Builder pattern and as usual I got confused with Factory pattern.

I have seen a good article which shows the difference between Abstract Factory and Builder pattern.

http://champika-nirosh.blogspot.in/2008/04/what-is-difference-between-abstract.html

But my confusion is that, more than Builder pattern similar to Abstract Factory I feel like it is similar to Factory Method pattern. Not sure my understanding is correct. But in Factory Method also we are using a separate factory (Method in Concrete Factory) to create one particular object (not a family of product). In that scenario how Builder differs from Factory Method pattern. I knew that Builder requires more steps to create object, other than that is there any particular scenario we need to use one over another? Please guide me.

Thanks.

Upvotes: 1

Views: 6565

Answers (1)

user1676075
user1676075

Reputation: 3086

Your particular usage case will affect which (if either) you might choose. But to essentially reiterate what's on the link you reference:

Both abstract factory and factory method are creating instances of unknown types. Generally these will be returning a class that corresponds to an interface, but you don't know (and shouldn't care) what the concrete type will be. To use the picture from that link, it's using a WindowsFactory, meaning the abstract factory is returning an instance that is compatible with Windows. If your factory were instead a LinuxFactory, you might get an object back that works on Linux. Note, also, that you probably wouldn't know if you had a LinuxFactory or WindowsFactory, just that you had a Factory of a particular type.

So the abstract factory & factory method patterns are about building polymorphic types (including when you don't know or care what the concrete type will be). However, the call to get an instance of the type is usually trivial. To build from a factory you're probably just calling:

MyInterfaceType myInstance = myFactory.getTheItemOfMyInterfaceType();

The builder pattern is more about building complex objects that may or may not be (but probably are) of a known type. In this case you'd expect a complex series of calls to construct the type, often setting one parameter after another. Because there's a lot of known parameters and arguments, you generally know what type of object you're going to get back from it (don't have to, but it's more likely than with an abstract factory). Builder is used when constructing the object is complex, but not necessarily polymorphic (it might be polymorphic, but that's not the premise of the pattern). A builder call to construct something might be (see Android AlertDialog for some real examples):

Builder b = new Builder();
b.setSomeValueA(myChoiceForA);
b.setSomeValueB(myChoiceForB);
MyInterfaceType myInstance = b.build();

Hope that helps.

Upvotes: 5

Related Questions