![](/img/trans.png)
[英]Why should the getInstance() method in Factory pattern be static?
[英]Abstract static factory method [getInstance()] in Java?
当然,以下内容在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(...);
}
}
要求Animal
类具有实例化自身的静态getInstance
方法的正确方法是什么? 这种方法应该是静态的; 一个“正常”的抽象方法在这里没有意义。
无法在抽象类(或接口)中指定实现类必须具有特定的静态方法。
使用反射可以获得类似的效果。
另一种方法是定义一个与Animal
类分开的AnimalFactory
接口:
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 {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.