Singleton Design Pattern

30
1



1. What is Singleton Design Pattern
2. Singleton as Creational Pattern
3. Implementation Guidelines
4. How do we implement a Singleton class

Text version of the video

Slides

Design Patterns Tutorial

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

This is continuation to Part 1 of Design Patterns Tutorial. So please watch Part 1 before proceeding.

Singleton Pattern belongs to Creational type pattern. As discussed in our previous video, Gang of four have defined five design patterns that belongs to creational design type category. Singleton is one among them and the rest are Factory, Abstract Factory, Builder and Prototype patterns. As the name implies, creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explain us the creation of objects in a manner suitable to a given situation.

Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application.

Advantages and Guidelines for Singleton implementation.

Concurrent access to the resource is well managed by singleton design pattern.

As part of the Implementation guidelines we need to ensure that only one instance of the class exists by declaring all constructors of the class to be private. Also, to control the singleton access we need to provide a static property that returns a single instance of the object.

Singleton Class Implementation Example

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// First version of Singleton demo
namespace SingletonDemo
{
class Program
{
static void Main(string[] args)
{
/*
* Assuming Singleton is created from employee class
* we refer to the GetInstance property from the Singleton class
*/
Singleton fromEmployee = Singleton.GetInstance;
fromEmployee.PrintDetails(“From Employee”);
/*
* Assuming Singleton is created from student class
* we refer to the GetInstance property from the Singleton class
*/
Singleton fromStudent = Singleton.GetInstance;
fromStudent.PrintDetails(“From Student”);

Console.ReadLine();
}
}
}

Singleton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonDemo
{
/*
* Sealed ensures the class being inherited and
* object instantiation is restricted in the derived class
*/
public sealed class Singleton
{
private static int counter = 0;

/*
* Private property initilized with null
* ensures that only one instance of the object is created
* based on the null condition
*/
private static Singleton instance = null;

/*
* public property is used to return only one instance of the class
* leveraging on the private property
*/
public static Singleton GetInstance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
/*
* Private constructor ensures that object is not
* instantiated other than with in the class itself
*/
private Singleton()
{
counter++;
Console.WriteLine(“Counter Value ” + counter.ToString());
}
/*
* Public method which can be invoked through the singleton instance
*/
public void PrintDetails(string message)
{
Console.WriteLine(message);
}
}
}

Nguồn:https://wijstaanvooronzegrondrechten.org/

Xem Thêm Bài Viết Khác:https://wijstaanvooronzegrondrechten.org/cong-nghe

30 COMMENTS

  1. I did not see that before.. Why you typed: public static name of the class(Singleton) instance = 0, same you did with that method named GetInstance. What is the use of putting the name of the class in there? Can you give me some documentation about that and explain me plase! And what is public static Singleton instance = null; it is a variabile ? what is that? i dint se no int, double, float.. etc

  2. Hi, I have a question about singleton classes. Suppose, I have a rest api based application and in that application i have created a databases connection class as singleton class. So, wanted to know, when ever a http request comes to fetch the user profile from the db. then on every request it creates a new instance or it uses the same instance for the database. if every time it create a new instance then what is the benefit of singleton class.

  3. we can also write in a single line like
    public static Singleton Instance=new Singleton() that time also constructor will call only once means only single instance is created right?
    so why we need to write more line of code is there any reason?

  4. Nice video , but i have doubt regarding properties and constructor and want to learn more about it .Can you provide me any reference for it.it will be really helpful, and also can anyone in the comment tell me, how the constructor was made into a property.Thanks in advance.

  5. I have a question. While I am trying to debug ,during first object creation itself the "instance" variable in Singleton class is filled with Singleton object. So my question is when the application is started, the static class is already loaded in the memory and the "static instance" variable is already initialized from null to new Singleton. Is that understanding correct?
    Anyone, please do confirm.

  6. Great video but I would likely want to do the check this way as it is a better practice

    if (instance != null) return instance;

    instance = new Singleton();

    return instance;

    Since most time won't be null. Let me know your opinion on this please. Thanks

  7. This tutorial is very misleading and confusing to beginners. You did not explain what is the real purpose of Singleton is and you implemented it wrong. A Singleton class has only ONE instance. You should not need to create instance of it to use it. The purpose of it is it should be used as a reference library of object only. To understand that clearly think of the Maths class. You do use created an instance of it you just use it. Maths.Round(value) etc
    You can use id to store constants for example and function to do basic calculations.
    You should declare the whole class as static and everything in it also as static.
    Using Employee as an example is confusing. Why do you need to make that a singleton give an example that make sense in real life.

  8. Thank you. This is good but its very basic. You need to show how to handle singleton when multiple clients are instantiating the class by implementing threads or with more newer version of Lazy loading.

  9. Hi,

    The video is very helpful in understanding the concept.

    I have a query.
    Suppose I have a singleton class which has static method which uses private variables in it to generate some id.

    public class SingletonClass {
    // assume private constructor and getInstance() method.
    private int id;

    public static int generateId(int num)
    {
    return id *num;
    }
    }

    Now if I want to change the value of id from another class how can I do this?

    public class AnotherClass extends SingletonClass {

    SingletonClass singleton = AnotherClass.getInstance(); // getting instance of SingletonClass

    public static int generateId(int num)
    {
    singleton.generateId();
    }

    }

    In the above method, how can I change the "id" to be present in the singleton method?

    Is there any way to do that?

LEAVE A REPLY

Please enter your comment!
Please enter your name here