Pattern question

cantabile cantabile.03 at wanadoo.fr
Fri Jul 8 11:53:56 CEST 2005


bruno modulix a écrit :

> You may want to have a look at the Factory pattern...
> 
> # outrageously oversimplified dummy exemple
> class Gui(object):
>    def __init__(self, installer):
>      self.installer = installer
> 
> class PosixGui(Gui):
>    pass
> 
> class Win32Gui(Gui):
>    pass
> 
> class GuiFactory(object):
>    def getGui(self, installer):
>       if os.name == 'posix':
>          return PosixGui(installer)
>       elif os.name == 'win32':
>           return Win32Gui(installer)
>       else:
>           raise "os %s not supported" % os.name
> 
> class Installer(object):
>    def __init__(self, guiFactory):
>       self.gui = guiFactory.getGui(self)
> 
> def main():
>    inst = Installer(GuiFactory())
>    return inst.gui.main()
> 
> NB 1:
> You may want to hide away the gui stuff:
> 
> class Installer(object):
>   def __init__(self):
>     self.gui = GuiFactory().getGui(self)
> 
>   def main(self):
>     return self.gui.main()
> 
> def main():
>   return Installer().main()
> 

Thanks for this, Bruno. It is much more elegant and adaptable than my
first attempt.
> 
> NB 2 :
> if it has to run in text mode, you should consider renaming "gui" to
> "ui", since a CLI is not really a 'graphical' ui !-)

You're right :))

> NB 3 :
> I made the GuiFactory a class, but it could also be a simple function.

> NB 4 :
> there are of course other solutions to the problem, which may or  not be
> more appropriate...
> 

Thanks a lot for these detailed explanations.



More information about the Python-list mailing list