|
| 1 | +class Klass1: |
| 2 | + """ a very simple obj """ |
| 3 | + def __init__(self): |
| 4 | + pass |
| 5 | + def hi(self): |
| 6 | + print 'hi' |
| 7 | + |
| 8 | +class Factory: |
| 9 | + """ base factory that can construct objects in a variety of ways: |
| 10 | + * modules ['package1.subpackage',] to be searched for klass |
| 11 | + * search global namespace |
| 12 | + * create takes a arguement of what type of class to return |
| 13 | + * return a default implementation - subclass must define createDefault() |
| 14 | + """ |
| 15 | + def __init__(self, modules=[]): |
| 16 | + self.modules=modules |
| 17 | + |
| 18 | + def createDefault(self): |
| 19 | + print dir() |
| 20 | + raise NotImplementedError |
| 21 | + |
| 22 | + def create(self, klass=None): |
| 23 | + import string |
| 24 | + if klass in globals().keys(): |
| 25 | + if type(globals()[klass]).__name__=='class': |
| 26 | + return globals()[klass]() |
| 27 | + for module in self.modules: |
| 28 | + try: |
| 29 | + fromlist = [] |
| 30 | + if string.find(module, '.'): fromlist = string.split(module, '.')[:-1] |
| 31 | + module = __import__(module, globals(), locals(), fromlist) |
| 32 | + if hasattr(module, klass): return getattr(module, klass)() |
| 33 | + except AttributeError: pass |
| 34 | + return self.createDefault() |
| 35 | + |
| 36 | +class MyFactory(Factory): |
| 37 | + """ concrete factory that specifies: |
| 38 | + * what modules to search for |
| 39 | + * implements a createDefault() - which is used if class isnt found |
| 40 | + """ |
| 41 | + def __init__(self, modules=[]): |
| 42 | + Factory.__init__(self,modules) |
| 43 | + def createDefault(self): |
| 44 | + return Klass1() |
| 45 | + |
| 46 | + |
| 47 | +#--------much simpler one by mark lutz, http://shell.rmi.net/~lutz/talk.html |
| 48 | +def factory(aClass, *args): # varargs tuple |
| 49 | + return apply(aClass, args) # call aClass |
| 50 | + |
| 51 | +class Spam: |
| 52 | + def doit(self, message): |
| 53 | + print message |
| 54 | + |
| 55 | +class Person: |
| 56 | + def __init__(self, name, job): |
| 57 | + self.name = name |
| 58 | + self.job = job |
| 59 | + |
| 60 | +object1 = factory(Spam) |
| 61 | +object2 = factory(Person, "Guido", "guru") |
0 commit comments