Can object instances know each other's current states?
I have 3 objects:
- Parser
- ParserState - a state machine that tracks the current state and transitions between states
- ParserDefinitions - it reads from a json file and supplies the regexes of a given state, as well as some other rules that govern how the parser operates
ParserState and ParserDefinitions are both subclasses (?) of Parser and are defined as Parser::ParserState and Parser::ParserDefinitions. It would be great if the ParserState object could have access to the current instance of ParserDefinitions and vice versa. Is this possible, or does it imply that they should actually be combined in to one class?
Btw, I am using Ruby so if it is possible that they share instance in开发者_如何学Goformation between them it would be great if Ruby code could be used.
Those are not subclasses, they are simply namespaced under the class. This provides no linkage between the class objects.
The way that object A accesses the state of object B is by invoking methods on object B and looking at the return values. It seems that the only issue here is how to make object A know about object B.
You have capitalized the names of these as though they are modules or classes, but you seem to be referring to them as instances. Are these singleton objects, or does (for example) a
Parser
instance create bothParserStart
andParserDefinitions
instances? Assuming that the latter is the case:class Parser attr_accessor :states, :defns def initialize self.states = ParserStates.new( self ) self.defns = ParserDefinitions.new( self ) end end class Parser::ParserStates attr_accessor :parser def initialize( parent_parser ) self.parser = parent_parser end def defns parser.defns end end class Parser::ParserDefinitions attr_accessor :parser def initialize( parent_parser ) self.parser = parent_parser end def states parser.states end end
Given the above, where each 'child' object knows about its 'parent' and the parent exposes accessors to the children, all objects can talk to one another.
精彩评论