user1056903
user1056903

Reputation: 941

Design - Alternative to not allowed abstract static method

I have an abstract class that contains a static method to check if a string fits to a certain type respectively implementation of AbstractType. If the string fits to a type, an object of the type class will be created by passing the string to the constructor.

Unfortunately it's not allowed to define abstract methods which are static. Can anyone recommend an design alternative?

Thanks in advance!

public abstract class AbstractType {

   public abstract static boolean isOfThisType(String str); // not possible

   ...

}

public class TypeA extends AbstractType {

   public static boolean isOfThisType(String str) {
   ...
   }

   ...

}

public class TypeB extends AbstractType {

   public static boolean isOfThisType(String str) {
   ...
   }

   ...

}

Upvotes: 0

Views: 339

Answers (2)

pickypg
pickypg

Reputation: 22332

SPI load an interface that has the method, and which can build the expected type on demand.

public interface MyType { /* your actual implementation */ }

public interface MyTypeChecker
{
    boolean isType(String value);
    MyType getType(String value);
}

public class MyTypeFactory
{
    public /* static */ MyType getType(String value)
    {
        MyType loaded = null;

        for (MyTypeChecker checker : ServiceLoader.load(MyTypeChecker.class))
        {
            if (checker.isType(value))
            {
                loaded = checker.getType(value);
                break;
            }
        }

        return loaded;
    }
}

Whether or not the Factory is static is largely irrelevant, although it tends to be more convenient. Depending on the rest of the design really determines its static nature. Personally, I prefer to avoid static whenever possible because it tends to lead to coupling of code.

If you were so inclined, then you could store the service loaded instances for future reuse (every call to ServiceLoader.load will instantiate a new object). This also allows the Factory to scale for new types by simply adding a new JAR with a defined SPI file, or adding the new type to the SPI file in the main JAR.

Upvotes: 0

duffymo
duffymo

Reputation: 308988

Yeah, don't make that a static method. If it needs to be polymorphic, don't make it static.

Since all of your classes will implement the static method, each and every one will shadow your abstract method's implementation. Provide a default implementation for the abstract class and let subclasses shadow it.

Upvotes: 1

Related Questions