Using the singleton design pattern
A group of authors now affectionately known as the ‘Gang of Four’ (Erich Gamma, Richard Helm, Ralph Johnson, and John Vilssides) wrote a book called ‘Design Patterns: Elements of Reusable Object-Oriented Software’. In this book they defined three categories of design patterns which are:
The Singleton Design pattern falls into the category of Creational Design Patterns, the Singleton Design Pattern ensures your software has only one instance of the class and provides a global access to it. In other words the Singleton design pattern is all about making sure that you can instantiate only one object of a particular class. If you don’t use a pattern like this one, the new operator just keeps on creating more and more objects.
Technically you could just use a static class as then there would only be one shared instance of a class for. However, if you did that then you would miss out on some of the benefits of the singleton design pattern. These benefits that singletons have over static classes include:
In object oriented programming and software development you generally create an instance of an object by using a new operator, for example:
C#: MyObject myNewInstance = new MyObject()VB.NET: Dim myNewInstance As New MyObject()
Each time a new object the computer allocates a heap of memory, creating lots of these object will increase the amount of memory is used and potentially effect the performance of your software product.
So how do we make it so that we only ever have one instance of our class, well it is a very simple 2 stage process:
C#:
public class MyObject{ //create a private static variale to store our instance private static MyObject singletonObject; //create a private constructor private MyObject() { //initial } //create a publi static method to return the instance public static MyObject CreateInstance() { //check if we already have an instance, if so return it, else create a new //instance if (singletonObject == null) singletonObject = new MyObject();
return singletonObject; }}
VB.NET :
Public Class MyObject ‘create a private static variale to store our instance Private Shared singletonObject As MyObject ‘create a private constructor Private Sub New() ‘initialise the object End Sub ‘create a public static method to return the instance Public Shared Function CreateInstance() As MyObject ‘check if we already have an instance, if so return it, else create a new ‘instance If singletonObject Is Nothing Then singletonObject = new MyObject() End If
Return singletonObject End FunctionEnd Class
Notice how in the implementation of the singleton design pattern we declare a private static variable to store the instance of our class. When we call the function we have created to create our instance a check is performed to see if an instance exists in that variable, if not one is created and returned.
Tags: Design, Pattern, singleton, Using
Posted in vb.net programming