Thursday, January 23, 2014

Singleton Pattern with Example

1. Singleton pattern falls under Creational Pattern .
2. Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

Singleton Example:
This is a class which is responsible for creating and maintaining its own unique instance.

Advantage vs Static calss
• we can create one instance of the object and reuse it.
• singleton class can have constructor.
• you can create the object of singleton class and pass it to method
• Singleton class does not say any restriction of Inheritance.
• We can dispose the objects of a singleton class but not of static class
• we can implement interface with Singleton class but not with Static class.

Syntax:
public class singleton
{
private singleton objInstance = new singleton();

private singleton() { }

public singleton GetInstance()
{
if (objInstance == null)
{
objInstance = new singleton();
}
return objInstance;
}

public string GetNames(string FirstName, string LastName)
{
return FirstName + ' ' + LastName;
}

}

Call from Mail Class:
string FullName = Singleton.GetSingleInstance().GetNames("Welcome", "Google");

No comments:

Post a Comment

Abstract Factory Vs Factory Method

Abstract Factory Provides an interface for creating families of related or dependent objects without specifying their concrete classes ...