The Visitor Pattern introduces a basic double dispatch mechanism to find the proper method inside the visitor that handles a specific class. Here is a small example implemented according to the GoF in terms of Delphi.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
unit uVisitorGoF; interface type TShapeVisitor = class; TAbstractShape = class public procedure Accept(Visitor: TShapeVisitor); virtual; abstract; end; TShapeRectangle = class(TAbstractShape) private FX0: Double; FX1: Double; FY0: Double; FY1: Double; public procedure Accept(Visitor: TShapeVisitor); override; property X0: Double read FX0 write FX0; property X1: Double read FX1 write FX1; property Y0: Double read FY0 write FY0; property Y1: Double read FY1 write FY1; end; TShapeCircle = class(TAbstractShape) private FCenterX: Double; FCenterY: Double; FRadius: Double; public procedure Accept(Visitor: TShapeVisitor); override; property CenterX: Double read FCenterX write FCenterX; property CenterY: Double read FCenterY write FCenterY; property Radius: Double read FRadius write FRadius; end; TShapeVisitor = class public procedure Visit(Instance: TAbstractShape); virtual; procedure VisitShapeCircle(Instance: TShapeCircle); virtual; abstract; procedure VisitShapeRectangle(Instance: TShapeRectangle); virtual; abstract; end; implementation procedure TShapeVisitor.Visit(Instance: TAbstractShape); begin Instance.Accept(Self); end; procedure TShapeCircle.Accept(Visitor: TShapeVisitor); begin Visitor.VisitShapeCircle(Self); end; procedure TShapeRectangle.Accept(Visitor: TShapeVisitor); begin Visitor.VisitShapeRectangle(Self); end; end. |
Thanks for an excellent article on the visitor pattern. I have heard a lot of talk regarding patterns, but all very abstract in its descriptions. This one really makes it easy to understand.
Jan