Programming - Singleton Design Pattern


Ensure a class has only one instance and provide a global point of access to it.
and
The classes and/or objects participating in this pattern are:
  • Singletonand
    and
  • 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.
// Singleton pattern -- Structural example

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;
}
}
}
and
Output expected:
Objects are the same instance
and
and


Home | Privacy Policy | Site Map | Links | Company | Contact Us | Arena           

We provide cutting edge software development, consultancy and web design services            

There are currently 652 user(s) with 40768 hits.