GoF定義
「定義一個能夠實行在一個物件架構中對於所有元素的操作。訪問者讓你可以定義一個新的操作,而不必更動到被操作元素的類別介面」
Visitor會去參訪所有有被收入的單位,以這個電腦的例子來說,這個Visitor實作的參訪對象就是Computer本身擁有的設備(Keyboard跟Monitor)跟自己本身
IComputerPart.cs
namespace LinXuan.DesignPattern.Example.Visitor
{
public interface IComputerPart
{
public void Accept(IComputerPartVisitor computerPartVisitor);
}
}
ComputerPartItem.cs
namespace LinXuan.DesignPattern.Example.Visitor
{
public class Computer : IComputerPart
{
IComputerPart[] parts;
public Computer()
{
parts = new IComputerPart[] { new Keyboard(), new Monitor() };
}
public void Accept(IComputerPartVisitor computerPartVisitor)
{
for (int i = 0; i < parts.Length; i++)
{
parts[i].Accept(computerPartVisitor);
}
computerPartVisitor.Visit(this);
}
public override string ToString()
{
return "Computer 1036";
}
}
public class Keyboard : IComputerPart
{
public void Accept(IComputerPartVisitor computerPartVisitor)
{
computerPartVisitor.Visit(this);
}
public override string ToString()
{
return "Keyboard 410";
}
}
public class Monitor : IComputerPart
{
public void Accept(IComputerPartVisitor computerPartVisitor)
{
computerPartVisitor.Visit(this);
}
public override string ToString()
{
return "Monitor 4833";
}
}
}
IComputerPartVisitor.cs
namespace LinXuan.DesignPattern.Example.Visitor
{
public interface IComputerPartVisitor
{
public void Visit(Keyboard keyboard);
public void Visit(Monitor monitor);
public void Visit(Computer computer);
}
}
ComputerPartDisplayVisitor.cs
using UnityEngine;
namespace LinXuan.DesignPattern.Example.Visitor
{
public class ComputerPartDisplayVisitor : IComputerPartVisitor
{
public void Visit(Keyboard keyboard)
{
Debug.Log("Visiting " + keyboard.ToString());
}
public void Visit(Monitor monitor)
{
Debug.Log("Visiting " + monitor.ToString());
}
public void Visit(Computer computer)
{
Debug.Log("Visiting " + computer.ToString());
}
}
}
VisitorTest.cs
using UnityEngine;
namespace LinXuan.DesignPattern.Example.Visitor
{
public class VisitorTest : MonoBehaviour
{
private void Start()
{
IComputerPart computer = new Computer();
computer.Accept(new ComputerPartDisplayVisitor());
}
}
}
輸出如下
設計模式與遊戲開發的完美結合(暢銷回饋版)
Turn Based Strategy Framework
流離之歌
Design Patterns - Visitor Pattern