« Visitor pattern » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
 
(3 versions intermédiaires par le même utilisateur non affichées)
Ligne 3 : Ligne 3 :
= Description =
= Description =
Allow adding new behaviors to existing class hierarchy without altering existing code.<br>
Allow adding new behaviors to existing class hierarchy without altering existing code.<br>
This pattern is particularly useful when, you cannot modify existing classes but need to change their behavior.
This pattern is particularly useful when, you cannot modify existing classes but need to add new features.


= Example =
= Example =
<filebox fn='User.cs'>
<filebox fn='User.cs'>
public class User : IUser
public class User
{
{
     public string Name { get; set; }
     public string Name { get; set; }
Ligne 26 : Ligne 26 :
public interface IVisitor
public interface IVisitor
{
{
     void Visit(Employee employee);
     void Visit(User user);
}
}
</filebox>
</filebox>
Ligne 40 : Ligne 40 :
     }
     }


     public void Visit(Employee employee)
     public void Visit(User user)
     {
     {
         employee.Name += $" ({this.Title})";
         user.Name += $" ({this.Title})";
     }
     }
}
}
</filebox>
</filebox>
<kode lang='cs'>
var user = new User("Nicolas");
Console.WriteLine(user.Name);  // Nicolas
user.Accept(new TitleVisitor("Boss"));
Console.WriteLine(user.Name);  // Nicolas (Big Boss)
</kode>

Dernière version du 3 avril 2022 à 20:47

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 add new features.

Example

User.cs
public class User
{
    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(User user);
}
TitleVisitor.cs
public class TitleVisitor : IVisitor
{
    public string Title { get; set; }

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

    public void Visit(User user)
    {
        user.Name += $" ({this.Title})";
    }
}
Cs.svg
var user = new User("Nicolas");
Console.WriteLine(user.Name);  // Nicolas

user.Accept(new TitleVisitor("Boss"));
Console.WriteLine(user.Name);  // Nicolas (Big Boss)