Home > Back-end >  Enum to return an implementation of an interface
Enum to return an implementation of an interface

Time:03-19

I have an interface called HeaderProvider and its implementations like this,

interface HeaderProvider {
    Map<String, String> getHeaders();
}

class AHeaderProvider implements HeaderProvider {
...
}
class BHeaderProvider implements HeaderProvider {
...
}

The implementations are Spring managed beans. Now I have an enum URLType

enum URLType{
A,
B....
}

Is there any way I can have a method inside the enum like HeaderProvider getHeaderProvider() which will return the correct implementation?

CodePudding user response:

Just add a HeaderProvider member to the enum

public enum URLType {
    A(new AHeaderProvider()), B(new BHeaderProvider());

    private HeaderProvider provider;

    private URLType(HeaderProvider provider) {
        this.provider = provider;
    }

    public HeaderProvider getHeaderProvider() {
        return provider;
    }
}

CodePudding user response:

I think you can do like this.

@Component
public class AHeaderProvider implements HeaderProvider, InitializingBean {

    private static HeaderProvider headerProvider;

    public static HeaderProvider getHeaderProvider() {
        return headerProvider;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        headerProvider = this;
    }

    @Override
    public Map<String, String> getHeaders() {
        return new HashMap<>();
    }
}

@Component
public class BHeaderProvider implements HeaderProvider, InitializingBean {

    private static HeaderProvider headerProvider;

    public static HeaderProvider getHeaderProvider() {
        return headerProvider;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        headerProvider = this;
    }

    @Override
    public Map<String, String> getHeaders() {
        return new HashMap<>();
    }
}

public enum UrlType {

    A(AHeaderProvider.getHeaderProvider()),

    B(BHeaderProvider.getHeaderProvider());
    private HeaderProvider headerProvider;

    UrlType(HeaderProvider headerProvider) {
        this.headerProvider = headerProvider;
    }


    public HeaderProvider getHeaderProvider() {
        return headerProvider;
    }
}
  • Related