简体   繁体   中英

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

Of course, the following 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's the correct way of requiring that Animal classes have a static getInstance method that instantiates itself? This method should be static; a "normal" abstract method doesn't make sense here.

There is no way to specify in an abstract class (or interface) that an implementing class must have a particular static method.

It is possible to get a similar effect using reflection.

One alternative is to define an AnimalFactory interface separate from the Animal class:

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 {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM