using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace DesignFactory.Visitor
{
/// <summary>
/// 访问者模式
/// </summary>
class VisitorPattern
{
}
abstract class Element
{
abstract public void Accept(Visitor visitor);
}
abstract class Visitor
{
abstract public void Visit(Element element);
}
class Employee : Element
{
public Employee(string name, double income, int vacationDays)
{
this.name = name;
this.income = income;
this.vacationDays = vacationDays;
}
public override void Accept(Visitor visitor)
{
visitor.Visit(this);
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private double income;
public double Income
{
get { return income; }
set { income = value; }
}
private int vacationDays;
public int VacationDays
{
get { return vacationDays; }
set { vacationDays = value; }
}
}
class IncomeVisitor : Visitor
{
public override void Visit(Element element)
{
Employee employee = (Employee)element;
employee.Income *= 1.10;
Console.WriteLine("{0}'s new income:{1:C}", employee.Name, employee.Income);
}
}
class VacationVisitor : Visitor
{
public override void Visit(Element element)
{
Employee employee = (Employee)element;
employee.VacationDays +=3;
Console.WriteLine("{0}'s new vacation days:{1:C}", employee.Name, employee.VacationDays);
}
}
class Employees
{
private ArrayList employees = new ArrayList();
public void Attach(Employee employee)
{
employees.Add(employee);
}
public void Detach(Employee employee)
{
employees.Remove(employee);
}
public void Accept(Visitor visitor)
{
foreach (Employee e in employees)
{
e.Accept(visitor);
}
}
}
public class VisitorApp
{
public static void Main(string[] args)
{
Employees e = new Employees();
e.Attach(new Employee("Hank", 25000.0, 14));
e.Attach(new Employee("Elly", 35000.0, 16));
e.Attach(new Employee("Dick", 45000.0, 21));
IncomeVisitor v1 = new IncomeVisitor();
VacationVisitor v2 = new VacationVisitor();
e.Accept(v1);
e.Accept(v2);
}
}
}
【设计模式】之 Visitor 观察者模式
最新推荐文章于 2025-03-25 22:19:19 发布