vendredi 26 janvier 2018

static factory methods inside interface

This is a design question regarding using static factory methods inside of static interface methods. I am looking for improvements or disadvantages of using this pattern.

public interface SampleService {

    // 1) do work
    void doWork();

    static SampleService create(final String service) {
        // 2)  Dispatch to factory method to get correct implementation
        return Factory.create(service);
    }

    class Factory {
        private static SampleService create(final String service) {
            // 3) return one of many possible implementations
            return new DefaultSampleService();
        }
    }

    class DefaultSampleService implements SampleService {
        @Override
        public void doWork() {
            // 4)  performs work
        }
    }
}

In original implementation, caller would call

SampleService.Factory.create

now they call it as

SampleService.create

Which looks to be cleaner and more readable. So what could we improve on this?

Aucun commentaire:

Enregistrer un commentaire