~doctormo/python-snippets/lp-merge-request-example

« back to all changes in this revision

Viewing changes to patterns/borg.py

  • Committer: sferguson
  • Date: 2010-01-12 19:04:45 UTC
  • mto: This revision was merged to the branch mainline in revision 14.
  • Revision ID: sferguson@ltsferguson2-20100112190445-elipmhvwjfxfli95
Add a Borg pattern snippet

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
#
 
3
# [SNIPPET_NAME: Borg]
 
4
# [SNIPPET_CATEGORIES: Patterns]
 
5
# [SNIPPET_DESCRIPTION: A module providing a basic implementation of the Borg pattern]
 
6
# [SNIPPET_AUTHOR: Scott Ferguson <scottwferg@gmail.com>]
 
7
# [SNIPPET_LICENSE: GPL]
 
8
 
 
9
"""This pattern ensures that all instances of a particular class share the same state"""
 
10
 
 
11
class Borg:
 
12
    _borg_state = {}
 
13
 
 
14
    def __init__(self):
 
15
        self.__dict__ = self._borg_state
 
16
 
 
17
# Sample code
 
18
 
 
19
class MyObject(Borg):
 
20
    _someProperty = 0
 
21
 
 
22
    @property
 
23
    def someProperty(self):
 
24
        return self._someProperty
 
25
 
 
26
    @someProperty.setter
 
27
    def someProperty(self, value):
 
28
        self._someProperty = value
 
29
 
 
30
if __name__ == '__main__':
 
31
    objectA = MyObject()
 
32
    objectB = MyObject()
 
33
 
 
34
    # Set the property of only object A
 
35
    objectA.someProperty = 5
 
36
 
 
37
    # Note that both A and B have the same value for someProperty
 
38
    print objectA.someProperty
 
39
    print objectB.someProperty