samedi 15 septembre 2018

Singleton Pattern In Python

I am new to Python and I am trying to learn this language by checking and creating examples of design patterns in Python.

I have a confusion with classic implementation of Singleton Pattern. Most of the articles out there mentions following implementation of Singleton as classic

class Singleton(object):
    name = None

    @staticmethod
    def instance():
        if '_instance' not in Singleton.__dict__:
            Singleton._instance = Singleton()

        return Singleton._instance


s1 = Singleton().instance();
s2 = Singleton().instance();

assert s1 is s2

But I am not fully convinced with this implementation because no where we are restricting users from creating multiple objects of Singleton class and I can still create an instance of this class by calling Singleton(). In Java, we prevent this by making constructor of class as Private.

Aucun commentaire:

Enregistrer un commentaire