![](/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.