主讲:李建忠
来源:http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/consyscourse/CsharpOOD.aspx
1: public abstract class Shape
2: {
3: public abstract void Draw();
4:
5: //预料到将来可能会引入新的操作
6: public abstract void Accept(ShapeVisitor v);
7: }
8:
9: public abstract class ShapeVisitor
10: {
11: public abstract void Visit(Rectangle shape); //#1
12: public abstract void Visit(Circle shape); //#2
13: public abstract void Visit(Line shape); //#3
14: }
15:
16: public class MyVisitor:ShapeVisitor
17: {
18: public override void Visit(Rectangle shape); //#1
19: {
20: //增加对Rectangle的操作
21: }
22:
23: public override void Visit(Circle shape); //#2
24: {
25: //增加对Circle的操作
26: }
27:
28: public override void Visit(Line shape); //#3
29: {
30: //增加对Line的操作
31: }
32: }
33:
34: public class Rectangle:Shape
35: {
36: public override void Draw()
37: {
38: //...
39: }
40:
41: public override void Accept(ShapeVisitor v)
42: {
43: v.Visit(this); //调用 #1
44: }
45: }
46:
47: public class Circle:Shape
48: {
49: public override void Draw()
50: {
51: //...
52: }
53:
54: public override void Accept(ShapeVisitor v)
55: {
56: v.Visit(this); //调用 #2
57: }
58: }
59:
60: public class Line:Shape
61: {
62: public override void Draw()
63: {
64: //...
65: }
66:
67: public override void Accept(ShapeVisitor v)
68: {
69: v.Visit(this); //调用 #3
70: }
71: }
72:
73: class App
74: {
75: ShapeVisitor visitor;
76: public App(ShapeVisitor visitor)
77: {
78: this.visitor=visitor;
79: }
80:
81: public static void Process(Shape shape)
82: {
83: //两处多态:
84: //1.Accept方法的调用对象 shape
85: //2.Accept等方法的参数 visitor
86: shape.Accept(visitor);
87: }
88: }
89:
90: App app=new App(new MyVisitor());
91: app.Process(new Line());