« Visitor pattern » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
(Page créée avec « Category:CSharp Category:Design Patterns = Description = Allow adding new behaviors to existing class hierarchy without altering existing code.<br> This pattern is… »)
 
Ligne 6 : Ligne 6 :


= Example =
= Example =
<filebox fn='User.cs'>
public class User : IUser
{
    public string Name { get; set; }
    public User(string name)
    {
        this.Name = name;
    }
    public void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}
</filebox>
<filebox fn='IVisitor.cs'>
public interface IVisitor
{
    void Visit(Employee employee);
}
</filebox>
<filebox fn='TitleVisitor.cs'>
public class TitleVisitor : IVisitor
{
    public string Title { get; set; }
    public TitleVisitor(string title)
    {
        this.Title = title;
    }
    public void Visit(Employee employee)
    {
        employee.Name += $" ({this.Title})";
    }
}
</filebox>

Version du 3 avril 2022 à 20:40

Description

Allow adding new behaviors to existing class hierarchy without altering existing code.
This pattern is particularly useful when, you cannot modify existing classes but need to change their behavior.

Example

User.cs
public class User : IUser
{
    public string Name { get; set; }

    public User(string name)
    {
        this.Name = name;
    }

    public void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}
IVisitor.cs
public interface IVisitor
{
    void Visit(Employee employee);
}
TitleVisitor.cs
public class TitleVisitor : IVisitor
{
    public string Title { get; set; }

    public TitleVisitor(string title)
    {
        this.Title = title;
    }

    public void Visit(Employee employee)
    {
        employee.Name += $" ({this.Title})";
    }
}