jeudi 1 octobre 2020

C#: Provider vs Factory class example

I am using class LoggerProvider to provide ILogger. For each concrete implementation of ILogger I am using specific named method. I am thinking about the structure, can I say this provider class is a factory class?

public class LoggerProvider
{
    public static ILogger GetDbLogger()
    {
        return new DBLogger();
    }

    public static ILogger GetEmailLogger(string email)
    {
        return new EmailLogger(email);
    }

    public static ILogger GetTxtLogger()
    {
        return new TxtLogger(new BaseTxtLoggerConfiguration(), ProjectManager.GetInstance().GetCurrentProjectSettings());
    }
}

public class CustomerOneService
{
    private readonly ILogger _logger;

    public CustomerOneService()
        : this(LoggerProvider.GetDbLogger())
    { }

    public CustomerOneService(ILogger logger)
    {
        _logger = logger;
    }

    public void Import()
    {
        // some operation with _logger
    }
}
public class CustomerTwoService
{
    private readonly ILogger _logger;

    public CustomerTwoService()
        : this(LoggerProvider.GetTxtLogger())
    { }

    public CustomerTwoService(ILogger logger)
    {
        _logger = logger;
    }

    public void CopyData()
    {
        // some operation with _logger
    }
}

Because if I understand purpose of Factory correctly, its used to provide instances of specific interface, but in runtime is decided which concrete implementation will be returned from Factory, for example some input from user interface which is passed to factory as parameter. But on the other hand another purpose is to provide instance and deal with the problem of creating objects - when client does not care how the instance was created. My provider applies this second principle, but not the first one.

I checked article Difference between a Factory, Provider and a Service? but according by definitions of factory and provider, I am still not sure which one is correct one for my case.

Aucun commentaire:

Enregistrer un commentaire