In which scenario are we using the Factory pattern and in which is the Singleton pattern?

Please help me understand the Factory pattern and Singleton pattern when we need to use the Factory pattern and when to use the Singleton pattern.

What is the main advantage / disadvantage of one over the other?

Any suggestion (explanation) will help me a lot.

+6
design-patterns
source share
2 answers

They do two very different things.

A Factory exists to create one or more copies of a class. He or the method he provides can be provided to another class that needs a dependency, and the dependent class can call the Factory method to get an instance.

One single exists to create one and ONLY one copy of the class. A class reference is obtained statically, but this reference can be passed as an instance, unlike a purely static class.

+2
source share

They are not very similar, and therefore they have no advantages over each other. If you are confused, first read:

Use the singleton pattern if you want only an instance of a single instance of an object class to be created.

Use the factory pattern when you need to ignore the details of instantiating your object class.

+3
source share

All Articles