« Bridge pattern » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Aucun résumé des modifications
Ligne 5 : Ligne 5 :


= Exemple =
= Exemple =
* The {{boxx|*Logger}} classes can be modified without modifying the {{boxx|UserService}} as long as it follows the {{boxx|ILogger}} contract.
<filebox fn='ILogger.cs'>
<filebox fn='ILogger.cs'>
public interface ILogger
public interface ILogger

Version du 6 juin 2020 à 22:25

Description

  • Decouple an abstraction from its implementation so that the two can vary independently.

Exemple

  • The *Logger classes can be modified without modifying the UserService as long as it follows the ILogger contract.
ILogger.cs
public interface ILogger
{
    void WriteLine(string text);
}
ConsoleLogger
public class ConsoleLogger : ILogger
{
    public void WriteLine(string text)
    {
        Console.WriteLine(text);
    }
}
IUserService.cs
public interface IUserService
{
    void ChangePassword(int userId, string newPassword);
}
UserService.cs
public class UserService : IUserService
{
    private ILogger logger;

    public UserService(ILogger logger)
    {
        this.logger = logger;
    }

    public void ChangePassword(int userId, string newPassword)
    {
        logger.WriteLine($"Password has been change for user {userId}.");
    }
}
Cs.svg
IUserService userService = new UserService(new ConsoleLogger());
userService.ChangePassword(1, "0000");