views:

89

answers:

2

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

What is the main advantage/disadvantage one over other?

Any suggestion(explanation) will help me lot. Thanks Vijendra Singh

+2  A: 

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

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.

Mike Atlas
+1  A: 

They do two very different things.

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

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

KeithS
@Keith:when we are using the Singleton pattern, only one instance of the class is created, that instance is common for all the users OR every user have own instance?
Vijjendra
@Vijjendra - "common for all users" OR "every user have their own instance" depends whether your executing code is in the same process or not. It has nothing to do with "users". If your process is a web application, a singleton instance may be the only instance for all requests, but if your web server starts another worker/task process, there could be another singleton instance in the memory space for that process as well.
Mike Atlas
@Mike:Thanks, mike please explain the second part(web server) scenario.
Vijjendra
@Vijjendra - That depends on your web server. Originally, your question was tagged with ASP.NET, so please read http://www.dotnetfunda.com/articles/article821-beginners-guide-how-iis-process-aspnet-request-.aspx
Mike Atlas