AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Implementation

The configuration manager, part by part, in four languages.

The point: five short parts. Each line below exists because something breaks without it.

Code

Build it in this order

The configuration manager, part by part

The class keeps the one object. It also keeps the lock that decides who builds.

import threadingclass ConfigManager:    """One set of settings for this process."""    _instance = None    _lock = threading.Lock()    builds = 0                      # how often the settings were loaded

Line 7

Empty at first. Because it belongs to the class, every caller looks at the same field. In Java it is volatile: without that word another thread may see the address before the content.

1 of 3

Why it is built this way

  • Name the class after its real job. ConfigSingleton tells the reader how it is made, not what it does.