-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproxypatterns.py
72 lines (59 loc) · 2.15 KB
/
proxypatterns.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from abc import ABCMeta, abstractmethod
import random
class AbstractSubject(object):
"""A common interface for the real and proxy objects"""
__metaclass__ = ABCMeta
@abstractmethod
def sort(self, reverse=False):
pass
class RealSubject(AbstractSubject):
def __init__(self):
self.digits = []
for i in xrange(100000):
self.digits.append(random.random())
def sort(self, reverse=False):
self.digits.sort()
if reverse:
self.digits.reverse()
"""A proxy class will be instatiated by the client code- which contains
the count of references to the RealSubject and keeps the only instance of
RealSubject creating only if it has not been created before.
In case it has been created, the reference counter is incremented!"""
class Proxy(AbstractSubject):
reference_count = 0
def __init__(self):
"""A constructor which creates an object if it is not exist and caches
it otherwise"""
if not getattr(self.__class__, 'cached_object', None):
self.__class__.cached_object = RealSubject()
print 'Created new object'
else:
print 'Using the cached object'
self.__class__.reference_count += 1
print 'Count of references = ', self.__class__.reference_count
def sort(self, reverse=False):
"""The args are logged by the proxy"""
print 'Called sort method with args: '
print locals().items()
self.__class__.cached_object.sort(reverse=reverse)
def __del__(self):
"""Decreases the reference"""
self.__class__.reference_count -= 1
if self.__class__.reference_count == 0:
print 'Number of reference_count is 0. Deleting the cached object..'
del self.__class__.cached_object
print 'Deleted object. Count of objects = ', self.__class__.reference_count
#client code
if __name__ == '__main__':
proxy1 = Proxy()
print
proxy2 = Proxy()
print
proxy3 = Proxy()
print
proxy1.sort(reverse=True)
print
print 'Deleting proxy2'
del proxy2
print
print 'the other objects are deleted upon program temrination'