访问者模式

本文通过一个具体实例展示了访问者模式的应用,使用C#实现了一个抽象的Person类和具体的Man、Woman子类,定义了不同的行为,并通过Action接口及其实现类Success来访问这些Person对象。
ExpandedBlockStart.gif代码
using System;
using System.Collections;
using System.Collections.Generic;

abstract class Action
{
    
public abstract void GetManConclusion(Man man);
    
public abstract void GetWomanConclusion(Woman woman);
}

class Success:Action
{
    
public override void GetManConclusion(Man man)
    {
        Console.WriteLine(
"{0}{1}时,背后多半有一个伟大的女人。", man.GetType().Name, this.GetType().Name);
    }
    
    
public override void GetWomanConclusion(Woman woman)
    {
        Console.WriteLine(
"{0}{1}时,背后多半有一个伟大的女人。", woman.GetType().Name, this.GetType().Name);
    }
}



abstract class Person
{
    
public abstract void Accept(Action action);
}

class Woman:Person
{
    
public override void Accept(Action action)
    {
        action.GetWomanConclusion(
this);
    }
}
class Man:Person
{
    
public override void Accept(Action action)
    {
        action.GetManConclusion(
this);
    }
}

class ObjectStructure
{
    
private IList<Person> elements=new List<Person>();
    
    
public void Add(Person element)
    {
        elements.Add(element);
    }
    
    
public void Detach(Person element)
    {
        elements.Remove(element);
    }
    
    
public void Display(Action voisitor)
    {
        
foreach(Person e in elements)
        {
            e.Accept(voisitor);
        }
    }
}



public class MyClass
{
    
public static void Main()
    {
        ObjectStructure o
=new ObjectStructure();
        o.Add(
new Man());
        
        Success v1
=new Success();
        o.Display(v1);
        
        Console.ReadLine();
    }
}


转载于:https://www.cnblogs.com/mikechang/archive/2010/04/15/1712634.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值