Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Vs Prototype - What to use when?

Both Factory & Prototype help in creating objects. When designing a new application:

  1. When would you use Factory Pattern over Prototype Pattern?
  2. When would you use Prototype Pattern over Factory Pattern?

I am quite confused which one to use where.

I know it can be very much problem specific but is there any general guideline?

Thoughts?

like image 410
Andy Avatar asked Nov 18 '13 08:11

Andy


People also ask

When would you use the prototype design pattern?

Prototype design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. Prototype pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs.

When factory methods are useful?

The Factory Method pattern is generally used in the following situations: A class cannot anticipate the type of objects it needs to create beforehand. A class requires its subclasses to specify the objects it creates. You want to localize the logic to instantiate a complex object.

Which pattern would you choose to create a clone or duplicate object?

The Prototype pattern lets you clone a prototype instead of asking a factory method to make a new object.


2 Answers

As i see it, although both are creational patterns, factory and prototype patterns are used in different contexts.

Factory pattern is used to introduce loose coupling between objects as the factory will take care of all the instantiation logic hiding it from the clients.

Prototype pattern on the other hand is used when the cost of creating an object is large and it is ok to copy an existing instance than creating a new instance.

like image 78
themanwhosoldtheworld Avatar answered Sep 25 '22 05:09

themanwhosoldtheworld


I am going to assume you're talking about the Abstract Factory design pattern (which shouldn't be confused with the Factory Method, which is another creational design pattern).

The difference between the two is not too obvious, for they can overlap and be used in a complementary way. Since the prototype creates a clone of itself, including all its properties, it is often created by an abstract factory just once, and then cloned for every necessary object (that will not require having its fields filled again).

Prototype thus avoids unnecessary "new" calls, for the objects are cloned and not created. In most modern OOP languages however, I wouldn't say it's such a big deal. My two cents : if you don't really see the difference, just keep on using the one you're used to implementing (that is, probably the abstract factory).

like image 37
Pierre Arlaud Avatar answered Sep 26 '22 05:09

Pierre Arlaud