模式角色与结构:
示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace CSharp.DesignPattern.VisitorPattern
{
class Program
{
static void Main(string[] args)
{
ObjectStructure list = new ObjectStructure();
list.AddEmployee(new FulltimeEmployee("Mike", ));
list.AddEmployee(new FulltimeEmployee("Tony", ));
list.AddEmployee(new ParttimeEmployee("Nancen", ));
list.AddEmployee(new ParttimeEmployee("Bibo", )); FinanceVisitor fVisitor = new FinanceVisitor();
HrVisitor hVisitor = new HrVisitor(); list.Accept(fVisitor);
list.Accept(hVisitor);
}
} class ObjectStructure
{
public void Accept(Visitor visitor)
{
foreach (IEmployee element in employees)
{
element.Accept(visitor);
}
} public void AddEmployee(IEmployee employee)
{
employees.Add(employee);
} public void RemoveEmployee(IEmployee employee)
{
employees.Remove(employee);
} private List<IEmployee> employees = new List<IEmployee>();
} class Visitor
{
public abstract void Visit(FulltimeEmployee fulltime);
public abstract void Visit(ParttimeEmployee contract);
} class FinanceVisitor : Visitor
{
public void Visit(FulltimeEmployee fulltime)
{
Console.Write("The wage of fulltime is ...");
}
public void Visit(ParttimeEmployee contract)
{
Console.Write("The wage of parttime is ...");
}
} class HrVisitor : Visitor
{
public void Visit(FulltimeEmployee fulltime)
{
Console.Write("The worktime of fulltime is ...");
Console.Write("The overtime of fulltime is ...");
Console.Write("The timeoff of fulltime is ...");
}
public void Visit(ParttimeEmployee contract)
{
Console.Write("The worktime of fulltime is ...");
}
} interface IEmployee
{
public void Accept(Visitor visitor)
{ } String Name { set; get; }
Int32 Wage { set; get; }
} class FulltimeEmployee : IEmployee
{
public FulltimeEmployee(String name, Int32 wage)
{
this._name = name;
this._wage = wage;
} public void Accept(Visitor visitor)
{
visitor.Visit(this);
} public void OperationFulltime()
{ } public string Name
{
get { return _name; }
set { _name = value; }
} public int Wage
{
get { return _wage; }
set { _wage = value; }
} private String _name;
private Int32 _wage;
} class ParttimeEmployee : IEmployee
{
public ParttimeEmployee(String name, Int32 wage)
{
this._name = name;
this._wage = wage;
} public void Accept(Visitor visitor)
{
visitor.Visit(this);
} public void OperationParttime()
{ } public string Name
{
get { return _name; }
set { _name = value; }
} public int Wage
{
get { return _wage; }
set { _wage = value; }
} private String _name;
private Int32 _wage;
}
}