65.9K
CodeProject is changing. Read more.
Home

Singleton

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (3 votes)

Oct 11, 2013

CPOL

1 min read

viewsIcon

8351

Singleton The Singleton Design Pattern ensures that only a single instance of a given object can exist.It does this by making the class

Singleton 

The Singleton Design Pattern ensures that only a single instance of a given object can exist.

It does this by making the class constructor private so that it [the singleton itself] has full control over when the class instance is created.  In order to gain access to an instance of a class that implements the Singleton pattern, the developer must call a shared/static method of that Singleton class.

A VB example of a Singleton

Public Class SingletonSample

 

    'shared members

    Private Shared _instance As New SingletonSample

 

    Public Shared Function Instance() As SingletonSample

        Return _instance

    End Function

 

    'instance members

    Private Sub New()

        'public instantiation disallowed

    End Sub

 

    'other instance members

    '...

 

End Class

A C# example of a Singleton

public class SingletonSample

{

    //shared members

    private static SingletonSample _instance = new SingletonSample();

 

    public static SingletonSample Instance()

    {

        return _instance;

    }

 

    //instance members

    private SingletonSample()

    {

        //public instantiation disallowed

    }

 

    //other instance members

    //...

}

 

With the Singleton Design Pattern in place, the developer can easily access that single object instance without needing to worry about inadvertently creating multiple instances, and provides a global point of access to it.

VB - Dim mySingleton As SingletonSample = SingletonSample.Instance

C# - SingletonSample mySingleton = SingletonSample.Instance();