Hay*_*mey 3 java abstract-class static-methods factory
当然,以下内容在Java中不起作用(没有抽象的静态方法)......
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(...);
}
}
Run Code Online (Sandbox Code Playgroud)
要求Animal类具有getInstance实例化自身的静态方法的正确方法是什么?这种方法应该是静态的; 一个"正常"的抽象方法在这里没有意义.
无法在抽象类(或接口)中指定实现类必须具有特定的静态方法.
使用反射可以获得类似的效果.
一种替代方法是定义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 {
// ...
}
Run Code Online (Sandbox Code Playgroud)