c版本的:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.forms;
using System.Data;
namespace WindowsApplication2
{
///
/// form1 的摘要说明。
///
public interface IVisitable
{
void accept(IVisitor visitor);
}
public interface IVisitor
{
void visit(IVisitable visitable);
}
public class VisitorA:IVisitor
{
public void visit(IVisitable visitable){
if (visitable is VisitableA){
MessageBox.Show(((VisitableA)visitable).Call(),"");
}
}
}
public class VisitableA:IVisitable
{
public String Call()
{
return "AAA";
}
public void accept(IVisitor visitor){
visitor.visit(this);
}
}
///
public class form1 : System.Windows.forms.form
{
private System.Windows.forms.Button button1;
///
/// 必需的设计器变量。
///
private System.ComponentModel.Container components = null;
public form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
///
/// 清理所有正在使用的资源。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
region Windows form Designer generated code
///
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///
private void InitializeComponent()
{
this.button1 = new System.Windows.forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(80, 72);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 272);
this.Controls.AddRange(new System.Windows.forms.Control[] {
this.button1});
this.Name = "form1";
this.Text = "form1";
this.ResumeLayout(false);
}
endregion
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.Run(new form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
IVisitor v=new VisitorA();
IVisitable vb=new VisitableA();
vb.accept(v);
}
}
}