samedi 2 mai 2020

Refactoring to factory method

I have a code block inside a function. I want to refactor this to apply the factory pattern.

        IService service;     

        switch (path)
        {
            case ServicePath.service1:
                service = new service1(log, mappingConfig);
                return await service.ServiceTask();
            case ServicePath.service2:
                service = new service2(log, mappingConfig);
                return await service.ServiceTask();
            case ServicePath.service3:
                service = new service3(log, mappingConfig);
                return await service.ServiceTask();
            case ServicePath.service4:
                service = new service4(log, mappingConfig);
                return await service.ServiceTask();
        }

What I have done is,

        class ServiceFactory
        {
            public static IService CreateService(String path, ILogger log, IConfig mappingConfig)
            {
                case ServicePath.service1:
                    return new service1(log, mappingConfig);
                case ServicePath.service2:
                    return new service2(log, mappingConfig);                    
                case ServicePath.service3:
                    return new service3(log, mappingConfig);
                case ServicePath.service4:
                    return new service4(log, mappingConfig);
            }
        }

and then, the caller method will be

    IService service = ServiceFactory.CreateService(path, log, mappingConfig);
    return await serviceFeature.ServiceTask();

So my concern is, is it still be a factory pattern? If not, how to refactor this to be a factory pattern?

And I am reading everywhere, Factory Pattern and Dependency Injection does the same work. How to implement my code for dependency injection ?

Aucun commentaire:

Enregistrer un commentaire