An improved method and system is described for implementing double dispatch extensibly and efficiently in single-dispatch object-oriented programming languages. Objects of type Visitor encapsulate double dispatch functionality, while objects of type Element act as operands. Double dispatch takes place by calling Accept on an object of type Element, passing an object of type Visitor as an argument. Concrete classes of type Element are added in groups, each group deriving from an abstract subclass of Element. An AbstractElement class augments the Element interface with an Accept operation that takes an object of type AppVisitor as an argument, where AppVisitor is an abstract subclass of Visitor. AppVisitor overrides the base class Visit operation to test the type of its Element argument, casting it into an AppElement and calling its augmented Accept. By committing to a client-specific AppVisitor interface as deeply in the Visitor class hierarchy as possible, the set of concrete element subclasses may be extended without changing the Visitor base class. Clients that rely on double dispatch are thus unaffected by such extension. Moreover, by calling the AbstractElement-augmented Accept rather than performing more extensive type tests for concrete Element subclasses, running time is improved over approaches that rely on more extensive type testing. Default functionality is easily accommodated as well.
展开▼