Abstract static factory method [getInstance ()] in Java?

Of course it doesn't work in Java (no abstract static methods) ...

public abstract class Animal {
    public abstract static Animal getInstance(byte[] b);
}

public class Dog extends Animal {
    @Override
    public static Dog getInstance(byte[] b) {
        // Woof.
        return new Dog(...);
    }
}

public class Cat extends Animal {
    @Override
    public static Cat getInstance(byte[] b) {
        // Meow.
        return new Cat(...);
    }
}

What is the correct way to require classes to Animalhave a static method getInstancethat instantiates itself? This method must be static; the "normal" abstract method does not make sense here.

+3
source share
1 answer

There is no way in an abstract class (or interface) to indicate that the implementation class must have a specific static method.

Using reflection, you can get a similar effect.

AnimalFactory Animal:

public interface AnimalFactory {
    Animal getInstance(byte[] b);
}

public class DogFactory implements AnimalFactory {
    public Dog getInstance(byte[] b) {
        return new Dog(...);
    }
}

public interface Animal {
    // ...
}

class Dog implements Animal {
    // ...
}
+6

Source: https://habr.com/ru/post/1755038/


All Articles