Singleton Pattern

[tr] Türkçe Oku

2023-06-11

Once upon a time, there was a ruler in the Singular Realm. The ruler’s name was “Singleton”, and he had the property of being the only entity in the whole realm. Singleton had educated everyone else about preserving his uniqueness and singularity.

Being the sole ruler of his kingdom, Singleton was recognized with the property of being a unique entity that, once created, could not be changed again. In every corner of the kingdom, it was known that Singleton was created only once and only one instance existed. This unique feature allowed Singleton to rule in his kingdom.

This story is implemented in the C# language as follows:

public class Singleton
{
    private static Singleton _instance;

    private Singleton() {}

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
}

The same story in Java language:

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

In Python:

class Singleton:
    _instance = None

    @staticmethod
    def getInstance():
        if Singleton._instance == None:
            Singleton()
        return Singleton._instance

    def __init__(self):
        if Singleton._instance != None:
            raise Exception("This class is a singleton!")
        else:
            Singleton._instance = self

This story in Go language:

package singleton

import "sync"

var instance *Singleton
var once sync.Once

type Singleton struct{}

func GetInstance() *Singleton {
    once.Do(func() {
        instance = &Singleton{}
    })
    return instance
}

This story in Rust language:

use std::sync::Mutex;

pub struct Singleton {
    //...
}

lazy_static! {
    static ref SINGLETON: Mutex<Singleton> = Mutex::new(Singleton {
        //...
    });
}

pub fn get_instance() -> &'static Mutex<Singleton> {
    &SINGLETON
}

And thus, the story of the Singleton design pattern is told. Singleton is a way of creating a single instance of a class and providing this single instance to the whole system. This is commonly used to manage global states or control shared resources. The Singleton pattern is used to prevent recurring creation operations, use resources efficiently, and provide consistency across the system.



More posts like this

The Dance of Components: The Composite Design Pattern

2023-06-22 | #composite-pattern #design-patterns #structural-patterns

Once upon a time, there was a tree in a forest. This tree was a complex structure with leaves and branches. Each branch could have smaller branches and leaves on it. The tree worked as a whole, holding its branches and leaves together. This tree is an example of the Composite design pattern. The tree (Composite) contains two types of components: branches (also Composite) and leaves (Leaf). Both branches and leaves implement the same interface (Component) recognized by the tree.

Continue reading 


Gaining Flexibility by Building Bridges: Analysis and Implementations in Four Different Languages with the Bridge Design Pattern

2023-06-22 | #bridge-pattern #design-patterns #structural-patterns

Once upon a time, there were two kingdoms. Despite being very close to each other, a wide and deep river was located between them. This river made it difficult for the kingdoms to interact with each other. To solve this situation, both kingdoms decided to build a bridge. This bridge became an interface that facilitated communication between the two kingdoms. However, the bridge had different structures and features on each side.

Continue reading 


Decorator Design Pattern: The Adornments of Software

2023-06-15 | #decorator-pattern #design-patterns #structural-patterns

Once upon a time, there was an object named “Component”. This object was used to perform a specific function. However, sometimes it was necessary to extend or modify this function. That’s where “Decorators” came into play. Decorators are objects that “decorate” or extend the Component. A Decorator comes on top of a Component and extends or modifies its function. This is used to extend the functionality of the Component without changing it itself.

Continue reading 