Summer_feeds
Just another WordPress.com weblog

Singleton Pattern


The singleton pattern is done to get the Object open for one instance only.There the object is made in static method inside the class.

Classes objects participating in the pattern as members. Load Balancer is a member in the pattern usage:

* defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
* responsible for creating and maintaining its own unique instance

The code samples are made available for C#.net and Java

using System;

namespace DoFactory.GangOfFour.Singleton.Structural
{

// MainApp test application

class MainApp
{

static void Main()
{
// Constructor is protected — cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

if (s1 == s2)
{
Console.WriteLine(“Objects are the same instance”);
}

// Wait for user
Console.Read();
}
}

// “Singleton”

class Singleton
{
private static Singleton instance;

// Note: Constructor is ‘protected’
protected Singleton()
{
}

public static Singleton Instance()
{
// Use ‘Lazy initialization’
if (instance == null)
{
instance = new Singleton();
}

return instance;
}
}
}

Answer = objects are the same instance

Java code organizer as given out
package com.designpatterns.Singleton;

public class Singleton {

public static void Main()
{
// Constructor is protected — cannot use new
Singleton s1 = new Singleton();
Singleton s2 = new Singleton();

if (s1 == s2)
{
System.out.println(“Objects are the same instance”);
}

// Wait for user
System.out.println();
}

// Note: Constructor is ‘protected’
protected Singleton()
{
}

public static Singleton Instance()
{
Singleton instance = null;
// Use ‘Lazy initialization’
if (instance == null)
{
instance = new Singleton();
}

return instance;
}
}

No Responses to “Singleton Pattern”

Leave a comment