Both Factory & Prototype help in creating objects. When designing a new application:
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?
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.
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.
The Prototype pattern lets you clone a prototype instead of asking a factory method to make a new object.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With