设计模式学习笔记——访问者模式(VIsitor)

1.特点:当Element较稳定、Visitor易增加时考虑。(朋友在精不在多)

2.概念:表示一个作用于某对象结构中的各个元素的操作。它使你可以在不改变各个元素的类的前提下定义作用于这些元素的新操作。

3.类图:

4.程序实现:

public abstract class Emploree
    {
        public string Name { get; set; }
        protected Emploree() { }
        public Emploree(string name)
        {
            Name = name;
        }
        public abstract void Accept(Visitor visitor);
    }

    public class Manager : Emploree
    {
        public Manager(string name)
        {
            Name = name;
        }
        public override void Accept(Visitor visitor)
        {
            visitor.Visit(this);
        }
    }

    public class Chairman : Emploree
    {
        public Chairman(string name)
        {
            Name = name;
        }
        public override void Accept(Visitor visitor)
        {
            visitor.Visit(this);
        }
    }

  

public abstract class Visitor
    {
        public abstract void Visit(Manager manager);
        public abstract void Visit(Chairman chairman);
    }

    public class Salary : Visitor
    {
        public override void Visit(Manager manager)
        {
            Console.WriteLine("Manager salary is 100000");
        }
        public override void Visit(Chairman chairman)
        {
            Console.WriteLine("Chairman salary is 1000000");
        }
    }

  

posted @ 2015-08-07 12:29  ice_baili  阅读(196)  评论(0编辑  收藏  举报