📄 visitorrealworld.cs
字号:
using System;
using System.Windows.Forms;
using System.Collections;
//访问者模式(Visitor pattern)
//意图
// 表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
//适用性
// 1.一个对象结构包含很多类对象,它们有不同的接口,而你想对这些对象实施一些依赖于其具体类的操作。
// 2.需要对一个对象结构中的对象进行很多不同的并且不相关的操作,而你想避免让这些操作“污染”这些对象的类。
// Visitor使得你可以将相关的操作集中起来定义在一个类中。当该对象结构被很多应用共享时,用Visitor模式让每个应用仅包含需要用到的操作。
// 3.定义对象结构的类很少改变,但经常需要在此结构上定义新的操作。改变对象结构类需要重定义对所有访问者的接口,
// 这可能需要很大的代价。如果对象结构类经常改变,那么可能还是在这些类中定义这些操作较好。
namespace DesignPattern.VisitorRealWorld
{
class VisitorRealWorld : AbstractPattern
{
public static void Run(TextBox tbInfo)
{
s_tbInfo = tbInfo;
s_tbInfo.Text = "";
// Setup employee collection
Employees e = new Employees();
e.Attach(new Clerk());
e.Attach(new Director());
e.Attach(new President());
// Employees are 'visited'
e.Accept(new IncomeVisitor());
e.Accept(new VacationVisitor());
// Wait for user
//Console.Read();
}
}
// "Visitor"
interface IVisitor
{
void Visit(Element element);
}
// "ConcreteVisitor1"
class IncomeVisitor : IVisitor
{
public void Visit(Element element)
{
Employee employee = element as Employee;
// Provide 10% pay raise
employee.Income *= 1.10;
DesignPattern.FormMain.OutputInfo("{0} {1}'s new income: {2:C}",employee.GetType().Name, employee.Name, employee.Income);
}
}
// "ConcreteVisitor2"
class VacationVisitor : IVisitor
{
public void Visit(Element element)
{
Employee employee = element as Employee;
// Provide 3 extra vacation days
DesignPattern.FormMain.OutputInfo("{0} {1}'s new vacation days: {2}", employee.GetType().Name, employee.Name, employee.VacationDays);
}
}
class Clerk : Employee
{
// Constructor
public Clerk() : base("Hank", 25000.0, 14)
{
}
}
class Director : Employee
{
// Constructor
public Director() : base("Elly", 35000.0, 16)
{
}
}
class President : Employee
{
// Constructor
public President() : base("Dick", 45000.0, 21)
{
}
}
// "Element"
abstract class Element
{
public abstract void Accept(IVisitor visitor);
}
// "ConcreteElement"
class Employee : Element
{
string name;
double income;
int vacationDays;
// Constructor
public Employee(string name, double income, int vacationDays)
{
this.name = name;
this.income = income;
this.vacationDays = vacationDays;
}
// Properties
public string Name
{
get{ return name; }
set{ name = value; }
}
public double Income
{
get{ return income; }
set{ income = value; }
}
public int VacationDays
{
get{ return vacationDays; }
set{ vacationDays = value; }
}
public override void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
// "ObjectStructure"
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(IVisitor visitor)
{
foreach (Employee e in employees)
{
e.Accept(visitor);
}
DesignPattern.FormMain.OutputInfo("");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -