Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main objective of using factory pattern?

Some of people recommend the factory pattern in java. I am not aware of that. What is the main objective to use the factory pattern in java and Give me your suggestion which type of pattern is useful?

like image 691
Venkat Avatar asked Feb 28 '23 10:02

Venkat


2 Answers

The objective depends on the type of factory pattern, e.g. Abstract Factory: "Provide an interface for creating families of related or dependent objects without specifying their concrete classes." from Design Patterns

Most factory patterns allow you to loosen the coupling between the creation request and the class of the object created. This allows you to reserve the right to change your mind.

This approach is commonly used to enable unit testing with stub or mock objects.

like image 75
richj Avatar answered Mar 03 '23 21:03

richj


There are 2 well know factory patterns:

  • Factory Method Pattern.
  • Abstract Factory Pattern.

Factory method pattern basically "deals with the problem of creating objects (products) without specifying the exact class of object that will be created." while Abstract Factory pattern "provides a way to encapsulate a group of individual factories that have a common theme."

Factory method is used for Object creation, basically creating a factory interface of methods which subclasses can derive and implement the method to create an object. This allows that encapsulation of not worrying who made the object but you have the object done once the method is excuted.

Abstract Factory pattern encapsulates Factories together who have the same objective functions to fulfill a task. E.g. you may have a Button GUI and have factory such as WindowFactory, LinuxFactory, AppleFactory that can create those buttons. Wrap these factory into an Abstract Factory such that, providing the OS, it will return a OS specific factory to create the Button.

Hope this is clear. Sorry for not using proper english constructive sentencing.

like image 32
Buhake Sindi Avatar answered Mar 03 '23 21:03

Buhake Sindi