root/patterns/proxy.py

Revision 4:9d7b78cb6e4c, 1.4 KB (checked in by Wayne Witzel <wayne@…>, 8 months ago)

for blog post 203

Line 
1'''
2    Quick implmentation of the Proxy (aka Surrogate) pattern [GoF94]
3   
4    [Gof94] Erich Gamma, Richard Helm, Ralph E. Johnson, John Vlissides (the Gang of Four)
5        Design Patterns - Elements of Object-Oriented Reusable Software Addison-Wesley
6        Reading, Massachusetts, 1994
7'''
8
9class File(object):
10    def load(self):
11        pass
12       
13class LargeFile(File):
14    def __init__(self, name):
15        self.name = name
16        self.load()
17       
18    def load(self):
19        print "Loading %s..." % (self.name)
20    def process1(self):
21        print "[phase1] Processing %s..." % (self.name)
22    def process2(self):
23        print "[phase2] Processing %s..." % (self.name)
24       
25class ProxyFile(File):
26    def __init__(self, name):
27        self.name = name
28        self.file = None
29       
30    def process1(self):
31        if not self.file:
32            self.file = LargeFile(self.name)
33        self.file.process1()
34
35    def process2(self):
36        if not self.file:
37            self.file = LargeFile(self.name)
38        self.file.process2()
39         
40def main():
41    f1 = ProxyFile("bigdb01.csv")
42    f2 = ProxyFile("bigdb02.csv")
43    f3 = ProxyFile("bigdb03.csv")
44   
45    f1.process1()
46    # some busines logic
47    f1.process2()
48    # more BL
49    f2.process2()
50    # more BL
51    f2.process1()
52    # Hey, we found what we needed, skipped f3
53    #f3.process()
54   
55if __name__ == '__main__':
56    main()
Note: See TracBrowser for help on using the browser.