Design Patterns in Python — SingleTon

This SingleTon pattern is very useful pattern when we need global instance of any service or class. This pattern is used to implement a class which returns only one instance every time when we try to create new instance.

Pattern Type — Creational Design Pattern

Benefits -

  • One and only one object is created
  • Object with global access to whole program
  • Controlling concurrent access to shared resources.

Now to implement this pattern to achieve SingleTon instance, we have 4 solutions and all of them are explained below one by one so, you can use any of them according to your programming style and your project/product.

Solution — 1 Using new method. new method is used to create new instance when we try to access this class.

Usage — To use this method to make your class SingleTon, You just need to copy new method to your class.

Method — 2 Monostate(Borg) pattern

Alex Martelli gave different solution to achieve this. Solution is called Monostate(‘Borg’) pattern. This method returns new instance every time but they share same properties(state) so ultimately it serves same purpose.

This solution is based on special variable of class dict. All properties of the object are stored in this special dict variable of class object. So we need to isolate dict variable for all the objects.

Usage — SingleTon itself is an example so if you want to use this method then just need to rename SingleTon class name to your class name as following.

Next two methods to achieve singleton pattern are very useful. Let’s look at them.

Method — 3 Create decorator to make any class singleton using callmethod.

Usage — Let’s use above decorator class and look how it can be used. Following is the example of usage -

Method — 4 Create metaclass to make any class singleton similar as previous method using __call__ method and type.

Usage — Let’s use metaclass and look how it can be used.

Now you can use any method from above methods according to your needs in your work.

Drawbacks -

  • Multiple references are created to same object
  • Global access of the object can leave developer confused sometimes from where the value is changed as the same object is used multiple places.

Thanks for reading this article. If you have any comments or questions please let me know in comment section.

Originally published on

Love podcasts or audiobooks? Learn on the go with our new app.