singleton pattern

singleton pattern (C#)

Introduction

In this report, I will try to delve into the singleton pattern. How to implement it and when and where it is useful to apply.


References

Singleton pattern


What does it do?

  1. The singleton pattern controls how many instances of a class can be createdTo control access to shared resources, such as a database connection or a file.

  2. Provide a global access point to that instanceWith simple global variable that store important content, this content may be overwritten almost by everything, however singleton allows the access, but it as well protects from overwriting it

note

this behavior is impossible to implement with a regular constructor since a constructor call must always return a new object by design


Implementation

  1. Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.

  2. Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.


Code example

// The Database class defines the `getInstance` method that lets
// clients access the same instance of a database connection
// throughout the program.
class Database is
    // The field for storing the singleton instance should be
    // declared static.
    private static field instance: Database

    // The singleton's constructor should always be private to
    // prevent direct construction calls with the `new`
    // operator.
    private constructor Database() is
        // Some initialization code, such as the actual
        // connection to a database server.
        // ...

    // The static method that controls access to the singleton
    // instance.
    public static method getInstance() is
        if (Database.instance == null) then
            acquireThreadLock() and then
                // Ensure that the instance hasn't yet been
                // initialized by another thread while this one
                // has been waiting for the lock's release.
                if (Database.instance == null) then
                    Database.instance = new Database()
        return Database.instance

    // Finally, any singleton should define some business logic
    // which can be executed on its instance.
    public method query(sql) is
        // For instance, all database queries of an app go
        // through this method. Therefore, you can place
        // throttling or caching logic here.
        // ...

class Application is
    method main() is
        Database foo = Database.getInstance()
        foo.query("SELECT ...")
        // ...
        Database bar = Database.getInstance()
        bar.query("SELECT ...")
        // The variable `bar` will contain the same object as
        // the variable `foo`.

Pros and Cons of the Singleton Pattern

Pros

Cons