0

I couldn't think of a good way to name this. Basically I'm have a program where I want to have a default "pattern" almost I guess of how something should function. But I wanted to allow the use to create their own implementation (This is like an API) of the class and use that as a parameter instead, with the functionality inside. Is this the most efficient way to do it? If you don't understand that bad description here is an example.

public class SimpleStyle extends AbstractStyle {

    public void personalizedImplementation() {
        // manipulate the program this way
    }

}

Then in the method

public static void do(Class<? extends AbstractSyle> style) {
    // Use reflection in herre to get the implementation and do it
}

Is there a better and more efficient way to do something like this

Elliott
  • 17
  • 2

1 Answers1

0

You should not use reflection for this task if you can avoid it. It is less readable and more error-prone than well designed interfaces.

The basic solution (I’m not sure whether you already considered it) is to simply pass instances of AbstractStyle to your method:

public static void doSomething(AbstractStyle style) {
    style.personalizedImplementation();
}

public static void main(String[] args) {
    do(new SimpleStyle());
}

If you cannot use this approach – this depends on the specific use case – you could define an additional interface that handles the creation of the AbstractStyle instance:

public interface StyleFactory {
    AbstractStyle createStyle();
}

public class SimpleStyleFactory implements StyleFactory {
    @Override
    public SimpleStyle createStyle() {
        return new SimpleStyle(/* ... */);
    }
}

public static void doSomething(StyleFactory styleFactory) {
    AbstractStyle style = styleFactory.createStyle();
    style.personalizedImplementation();
}

public static void main(String[] args) {
    do(new SimpleStyleFactory());
}

Note: do is a Java keyword, so it can’t be used as an identifier. I used doSomething instead.

Robin Krahl
  • 5,268
  • 19
  • 32
  • I never see the benefit of that builder patter, wouldn't it be better to have an abstract method in the `AbstractStyle` for `createStyle` to force the class to have a static method to create a new instance, instead of all the boilerplate code of the factory interface and multiple factories for the different implementations – Elliott Jun 08 '16 at 23:03
  • @Elliott I would agree, but static methods can't be inherited. That means you can't force `SimpleStyle` to have a static `createStyle` method, and even if it has one, you can't call it safely in a generic way. – Robin Krahl Jun 08 '16 at 23:57
  • @Elliott declaring a method as `static abstract` should raise a compiler error. See [this question](http://stackoverflow.com/questions/370962/why-cant-static-methods-be-abstract-in-java) for details. – Robin Krahl Jun 08 '16 at 23:58