Greg
Greg

Reputation: 1719

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?

Upvotes: 1

Views: 1512

Answers (1)

Soeren
Soeren

Reputation: 1829

I recommend not to put the factory into the Interface for the following reason:

It violates the Open-Closed-principle (https://en.wikipedia.org/wiki/Open/closed_principle).

A client, working with the Interface SampleService, doesn't wan't that the Interface(file) to change frequently. That is always a source of errors.

A factory method in an Interface is therefore not a good programming style (in my opinion). I suggest to split the Interface and Factory into two different classes. Possible clients don't have to know if new subtypes are created and in that way the volatile part of the program is capsulate in the Factory class.

Upvotes: 1

Related Questions