访问者模式:

  访问者模式(Visitor),表示一个作用于某个对象结构中各元素的操作,它使你可以再不改变各元素类的前提下定义作用于这些元素的新操作。

 

结构图:

                             

 

代码图:

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 访问者模式
{
    class Program
    {
        static void Main(string[] args)
        {

            ObjectStructure o = new ObjectStructure();
            o.Attach(new Man());
            o.Attach(new Woman());

            Success v1 = new Success();
            o.Display(v1);
            Console.Read();
        }
    }

    //abstract class Person
    //{
    //    protected string action
    //    {
    //        get { return action; }
    //        set { action = value; }
    //    }

        abstract class Action
        {
            public abstract void GetManConclusion(Man concreteElementA);

            public abstract void GetWomanConclusion(Woman concreteElementB);
        }
    abstract class Person
    {
        public abstract void Accept(Action visitor);
    }

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

        public override void GetWomanConclusion(Woman concreteElementB)
        {
            Console.WriteLine("{0}  {1},时,背后多半有一个不成功的男人!", concreteElementB.GetType().Name, this.GetType().Name);
        }
    }
    class Man : Person
    {
        public override void Accept(Action visitor)
        {
            visitor.GetManConclusion(this);
        }
    }
    class Woman : Person
    {
        public override void Accept(Action visitor)
        {
            visitor.GetWomanConclusion(this);
        }
    }

    class ObjectStructure
    {
        private IList<Person> elements = new List<Person>();

        public void Attach(Person element)
        {
            elements.Add(element);
        }

        public void Display(Action visitor)
        {
            foreach (Person e in elements)
            {
                e.Accept(visitor);
            }
        }
    }
}

 

 

 


本文转载:CSDN博客