|
1 | 1 | #!/usr/bin/env python
|
2 | 2 | # -*- coding: utf-8 -*-
|
3 | 3 |
|
| 4 | +""" |
| 5 | +*What is this pattern about? |
| 6 | +The Borg pattern (also known as the Monostate pattern) is a way to |
| 7 | +implement singleton behavior, but instead of having only one instance |
| 8 | +of a class, there are multiple instances that share the same state. In |
| 9 | +other words, the focus is on sharing state instead of sharing instance |
| 10 | +identity. |
| 11 | +
|
| 12 | +*What does this example do? |
| 13 | +To understand the implementation of this pattern in Python, it is |
| 14 | +important to know that, in Python, instance attributes are stored in a |
| 15 | +attribute dictionary called __dict__. Usually, each instance will have |
| 16 | +its own dictionary, but the Borg pattern modifies this so that all |
| 17 | +instances have the same dictionary. |
| 18 | +In this example, the __shared_state attribute will be the dictionary |
| 19 | +shared between all instances, and this is ensured by assigining |
| 20 | +__shared_state to the __dict__ variable when initializing a new |
| 21 | +instance (i.e., in the __init__ method). Other attributes are usually |
| 22 | +added to the instance's attribute dictionary, but, since the attribute |
| 23 | +dictionary itself is shared (which is __shared_state), all other |
| 24 | +attributes will also be shared. |
| 25 | +For this reason, when the attribute self.state is modified using |
| 26 | +instance rm2, the value of self.state in instance rm1 also chages. The |
| 27 | +same happends if self.state is modified using rm3, which is an |
| 28 | +instance from a subclass. |
| 29 | +Notice that even though they share attributes, the instances are not |
| 30 | +the same, as seen by their ids. |
| 31 | +
|
| 32 | +*Where is the pattern used practically? |
| 33 | +Sharing state is useful in applications like managing database connections: |
| 34 | +https://github.com/onetwopunch/pythonDbTemplate/blob/master/database.py |
| 35 | +
|
| 36 | +*References: |
| 37 | +https://fkromer.github.io/python-pattern-references/design/#singleton |
| 38 | +
|
| 39 | +""" |
| 40 | + |
4 | 41 |
|
5 | 42 | class Borg(object):
|
6 | 43 | __shared_state = {}
|
|
0 commit comments