| 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 | |
|---|
| 9 | class File(object): |
|---|
| 10 | def load(self): |
|---|
| 11 | pass |
|---|
| 12 | |
|---|
| 13 | class 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 | |
|---|
| 25 | class 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 | |
|---|
| 40 | def 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 | |
|---|
| 55 | if __name__ == '__main__': |
|---|
| 56 | main() |
|---|