Python — Five Ways to Write Singleton

How to write singleton pattern in Python

Tony
Geek Culture

--

Why Singleton Pattern

The Singleton Pattern is a common software design pattern whose main purpose is to ensure that only one instance of a class exists. Singleton objects come in handy when you want only one instance of a class to appear in the entire system.

For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class.

If the content of the configuration file needs to be used in many places during the running of the program, that is to say, instances of the AppConfig object need to be created in many places, which leads to the existence of multiple AppConfig instance objects in the system, which will seriously waste memory resources, especially if the configuration file has a lot of content.

In fact, for a class like AppConfig, we want only one instance of the object to exist during the runtime of the program.

5 Ways to Write Singleton in Python

In Python, we can implement the singleton pattern in several ways:

Use modules

--

--