设计模式之访问者模式

封装某些作用域某种数据结构中的各元素的操作。它可以再不改变数据结构的前提下定义这些元素的新的操作。

 

 

 

    abstract class Element
    {
        public abstract void Accept(IVisitor visitor);
        public abstract void DoSomething();

    }

    class ConcreteElement1 : Element
    {
        public override void DoSomething()
        {
            Console.WriteLine("This is element 1");

        }
        public override void Accept(IVisitor visitor)
        {
            visitor.visit(this);
        }
    }

    class ConcreteElement2 : Element
    {
        public override void DoSomething()
        {
            Console.WriteLine("This is element 2.");
        }
        public override void Accept(IVisitor visitor)
        {
            //throw new NotImplementedException();
            visitor.visit(this);
        }
    }


    interface IVisitor
    {
        void visit(Element visitor);
    }

    class Visitor : IVisitor
    {
        public void visit(Element el)
        {
            el.DoSomething();
            Console.WriteLine("Visited!");
        }
    }
    class Visitor1 : IVisitor
    {
        public void visit(Element el)
        {
            el.DoSomething();
            Console.WriteLine("Visited1!");
        }
    }

    class ObjectStructure
    {
        public static List<Element> getList()
        {
            List<Element> list = new List<Element>();
            Random rd = new Random();
            for (int i = 0; i < 10; i++)
            {
                int a = rd.Next(100);
                if (a >= 50)
                {
                    list.Add(new ConcreteElement1());
                }
                else
                {
                    list.Add(new ConcreteElement2());
                }
            }
            return list;
        }
    }

    class P
    {
        public static List<Thread> tds = new List<Thread>();
        public static void Main(string[] str)
        {
            List<Element> list = ObjectStructure.getList();
            foreach (Element element in list)
            {
                if (element is ConcreteElement1)
                {
                    element.Accept(new Visitor1());
                }
                else
                {
                    element.Accept(new Visitor());
                }
            }
        }
    }

posted on 2014-07-16 10:40  Henry_Wang  阅读(146)  评论(0编辑  收藏  举报

导航