What is the difference between Factory Pattern and Singleton Pattern?

 Posted by Niladri.Biswas on 7/19/2012 | Category: Design Pattern & Practices Interview questions | Views: 7235 | Points: 40

Singleton pattern ensures only one instance of the type always be available for the client(s).Let us look into the below code

class Singleton


private static Singleton singletonInstance;

private Singleton(){}

public static Singleton CreateInstance()

return singletonInstance == null ? new Singleton() : singletonInstance;

The constructor is defined as private ensuring that no instance of the class can be created. Singleton keeps common data in only one place and this can be done by using the "static" keyword where the property "Singleton" is defined.Next checking if the property value is null or not.If yes then we are creating an instance and if no then we are returning back the old instance only.This is done inside the CreateInstance method The client invocation part is as under

var _singletonInstance = Singleton.CreateInstance();

The factory pattern deals with how an object is created. It gets classified under the creational pattern.We can go for a factory pattern when we need for

a) Object creation without exposing it to client

b) Refer to newly created objects through interface.

Factory pattern defines an interface for creating an object, but let the classes that implement the interface decide which class to instantiate.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response