访问者模式:表示一个作用于某对象结构中各元素的操作。它使你可以在不改变个元素的前提下定义作用于这些元素的新操作。
对象结构不能变,必须是固定的。
public abstract class Element
{
public abstract void Accept(Visitor visitor);
}
public class ConcreteElementA : Element
{
public override void Accept(Visitor visitor)
{
visitor.VisitConcreteElementA(this);
}
}
public class ConcreteElementB : Element
{
public override void Accept(Visitor visitor)
{
visitor.VisitConcreteElementB(this);
}
}
public abstract class Visitor
{
public abstract void VisitConcreteElementA(ConcreteElementA concreteElementA);
public abstract void VisitConcreteElementB(ConcreteElementB concreteElementB);
}
public class ConcreteVisitorA : Visitor
{
public override void VisitConcreteElementA(ConcreteElementA concreteElementA)
{
System.Console.WriteLine("aaa");
}
public override void VisitConcreteElementB(ConcreteElementB concreteElementB)
{
System.Console.WriteLine("bbb");
}
}
public class ConcreteVisitorB : Visitor
{
public override void VisitConcreteElementA(ConcreteElementA concreteElementA)
{
throw new System.NotImplementedException();
}
public override void VisitConcreteElementB(ConcreteElementB concreteElementB)
{
throw new System.NotImplementedException();
}
}
public class ConcreteVisitorC : Visitor
{
public override void VisitConcreteElementA(ConcreteElementA concreteElementA)
{
throw new System.NotImplementedException();
}
public override void VisitConcreteElementB(ConcreteElementB concreteElementB)
{
throw new System.NotImplementedException();
}
}
public class ObjectStruct
{
private List<Element> elements = new List<Element>();
public void Attach(Element element)
{
elements.Add(element);
}
public void Detach(Element element)
{
elements.Remove(element);
}
public void Accept(Visitor visitor)
{
foreach (var item in elements)
{
item.Accept(visitor);
}
}
}
class Program
{
static void Main(string[] args)
{
ObjectStruct objectStruct = new ObjectStruct();
objectStruct.Attach(new ConcreteElementA());
objectStruct.Attach(new ConcreteElementB());
ConcreteVisitorA a = new();
ConcreteVisitorB b = new();
objectStruct.Accept(a);
objectStruct.Accept(b);
Console.WriteLine("Hello World!");
}
}