[Tutor] OO approach to solving problem?

antonmuhin на rambler.ru antonmuhin на rambler.ru
Wed Jan 8 04:59:01 2003


Hello Brad,

Wednesday, January 8, 2003, 12:32:15 AM, you wrote:

BR> Does the above approach sound reasonable?
Rather reasonable. However, see several notes below.

BR> If so, I think I know how to address most of the issues. However, I am
BR> unclear as to how the creature instances can communicate with the master
BR> class. How does the instance 'know' who created it and how to pass
BR> information back to it? I'm sure this must be a common design pattern, but
BR> being an old-time Fortran programmer, I haven't acquired much OO experience.
There are several approaches. One of most simple may be to have a
reference to the 'master' object. Something like:

class BeastMaster:
      def isGoingToDie(self, creature):
          print "Creature", creature, "is going to die!"
          # Sure, you need something else here

class BasicCreature:
      def __init__(self, master):
          self.master = master

      def onDie(self):
          self.master.isGoingToDie(self)

class Moth(BasicCreature):
      def someMethod(self):
          # It's going to die...
          self.onDie()

Actually there is  kind of general pattern: Observer pattern (google
for it and you'll find a lot).

In some cases weak references may be more useful, though I don't think
it pertains to your problem as you described it.

Another thing that should be thought out is managing parallelism. As
you described your problem it seems that creatures should live their
life in parallel. There are several approaches to it. You may use
threads and alike stuff. However, there would appear a lot of problems
with locks, synchronization (though you may be much better in parallel
programming than me, and it'd be really easy for you :) ).

There is simpler approach that in CPython seems to be quicker too: you
may use generators to dispatch process quants to creatures. If you
need more info, please, write.

-- 
Best regards,
 antonmuhin                            mailto:antonmuhin@rambler.ru