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;
}
}

Advertisements

No Responses to “Singleton Pattern”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: