views:

92

answers:

3

Hi, I'm new to design patterns and I cant really see a difference between this two patterns, both are creational patterns arent they? and what is the purpose of each pattern? thanks.

+1  A: 

A singleton pattern ensures that you always get back the same instance of whatever type you are retrieving, whereas the factory pattern generally gives you a different instance of each type.

The purpose of the singleton is where you want all calls to go through the same instance. An example of this might be a class that manages a disk cache, or gets data from a static dictionary; wherever it is important only one known instance interacts with the resource. This does make it less scalable.

The purpose of the factory is to create and return new instances. Often, these won't actually be the same type at all, but they will be implementations of the same base class. However, there may be many instances of each type

Rob Levine
A bit of a nickpick - a singleton relates to the lifecycle of the object (only one in this case - probably for life of the application).A factory's job is to return objects that you require - it will often build a new instance of a type, but not neccessarily so - one could move the lifecycle control of the singleton out of the singleton class and put it into a factory instead which could return the same class everytime making it essentially a singleton for your application
saret
A: 

Singleton pattern is a pattern whose purpose is to ensure that no matter how many times a client (or multiple clients) ask for an instance of this specific Type to be created (instantiated) for them, they will always get the exact same one and only one instance of the type. It guarantees that only one instance of the type can ever be instantiated (like for instance if the Type is managing a 200 MByte in memory cached copy of some data structure - you only want one copy to exist) A Singleton Type will generally have a factory method in it, to deliver to requesting clients that one and only one instance.

A Factory method is a method that encapsulates the creation or instantiation of a type so that the type itself has control over how it is instantiarted.

Charles Bretana
A: 

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.

Matt Davis