From: Daniel Schierbeck Date: 2005-11-28T07:27:28+09:00 Subject: Re: Object access heirarchies Leslie Viljoen wrote: > I often have this problem in my projects. > > I have a bunch of classes to do various things in my program, but > once instantiated they each need access to each other. For example, > in the adventure game I am working on, I have a Parser object that > needs to manipulate a Player, Map and Things in the map. > > I normally do such things by passing objects around when initializing, > like so: > > parser = Parser(Player.new(World.new(Map.new, Things.new))) > > That works, although it seems a little long winded - for the > parser to modify a thing, it needs to set something like: > player.world.thing["ball"].name = "bat" > > Later, the Things needed access to the Map so I could set thing.location > to a map.room object. So I changed thing.location to be a string -- > thing.location_name and made a function that could look up a location > based on it's name: map["garden"]. > > What I want to know is: what's the best way? I had globals $player, > $world, $map > earlier and that makes things a bit easier but it also makes me nervous > (perhaps just because I have been anti-global-indoctrinated for 20 years > now) > I'm still a bit vague on Modules. Any ideas? > > Les What about a single base class? class Game attr_reader :parser, :world, :map, :things, :player def initialize @parser = Parser.new(self) @world = World.new(self) @map = Map.new(self) @things = Things.new(self) @player = Player.new(self) end class World def initialize(game) @game = game end def map @game.map end # .... end # .... end Cheers, Daniel