Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which scenario do we use the Factory Pattern and in which the Singleton Pattern?

Please help me to understand the Factory pattern and the 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 lot.

like image 797
Vijjendra Avatar asked Sep 27 '10 21:09

Vijjendra


People also ask

In which scenario we can use singleton pattern?

Singleton pattern is used for logging, drivers objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc. Singleton design pattern is used in core java classes also, for example java. lang.

Why use an object factory and how would you implement the singleton pattern?

Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.

What is a factory pattern and how would you implement the singleton pattern?

The Singleton pattern ensures that only one instance of the class exists and typically provides a well-known, i.e., global point for accessing it. The Factory pattern defines an interface for creating objects (no limitation on how many) and usually abstracts the control of which class to instantiate.

When we use Singleton design pattern give real time example?

For example running a trial version of a software with one license and one database connection ,that uses singleton pattern in real word.

Why do we need to use singleton factory?

The purpose of the Singleton Design pattern is to return the same object over and over to the caller. Singleton would be useful when you need to have an access to same object in the different part of an application.

Where do we use factory design pattern?

The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class.


1 Answers

They're not very similar, and thus they don't have advantages over one another. If you're confused, read up first:

  • Singleton Pattern - Wikipedia
  • Factory Pattern - Wikipedia

Use the singleton pattern when you wish to only allow one instance of an object class to be instantiated.

Use the factory pattern when you need to abstract out the details of instantiation of your object's class.

like image 192
Mike Atlas Avatar answered Oct 14 '22 07:10

Mike Atlas