课程: Python: Design Patterns

免费学习该课程!

今天就开通帐号,24,700 门业界名师课程任您挑!

Singleton

Singleton

- [Presenter] According to the Gang of Four definition, singleton is the pattern you need when you want to allow only one object to be created from a class. It's an object-oriented way of providing global variables. A similar concept called Borg exists in the Python community. Unlike singleton, Borg allows multiple object instances, but they all share the same state, which means the same attribute values in the objects. Borg is a short for Cyborg, prominently featured in the "Star Trek" series. They share collective thoughts like objects in the Python Borg pattern. Why would you need a pattern like singleton or Borg? Let's say that there is a need for keeping a cache of information to be shared by various elements of your software system. By keeping this information in a single object like singleton or sharing it constantly in Borg objects, there's no need to retrieve the information from its original sources each time. All modules in Python act as singletons. In our scenario, Borg…

内容