4
Q
靜態工廠方法
A
回答
5
public class Foo {
public Foo() {
// If this is called by someone saying "new Foo()", I must be a Foo.
}
}
public class Bar extends Foo {
public Bar() {
// If this is called by someone saying "new Bar()", I must be a Bar.
}
}
public class FooFactory {
public static Foo buildAFoo() {
// This method can return either a Foo, a Bar,
// or anything else that extends Foo.
}
}
1
讓我打破你的問題分兩部分
(1)與構造,他們可以回到他們的返回類型的任何亞型的對象
(2),讓你在選擇了極大的靈活性返回對象的類。
比方說您已經從Player
這是PlayerWithBall
和PlayerWithoutBall
public class Player{
public Player(boolean withOrWithout){
//...
}
}
//...
// What exactly does this mean?
Player player = new Player(true);
// You should look the documentation to be sure.
// Even if you remember that the boolean has something to do with a Ball
// you might not remember whether it specified withBall or withoutBall.
to
public class PlayerFactory{
public static Player createWithBall(){
//...
}
public static Player createWithoutBall(){
//...
}
}
// ...
//Now its on your desire , what you want :)
Foo foo = Foo.createWithBall(); //or createWithoutBall();
這裏擴展兩個類你會得到兩個答案的flexability和不像構造行爲 現在你可以看到通過這些工廠方法它取決於你,你需要哪種類型的球員
相關問題
- 1. 靜態工廠方法vs工廠
- 2. AutoMapper靜態工廠方法
- 3. 靜態工廠方法(Spring)
- 4. 靜態工廠方法
- 5. Autofac工廠靜態方法
- 6. 靜態工廠方法
- 7. 創建一個從靜態工廠方法工廠,然後調用靜態工廠方法上的ID
- 8. Spring 3 @Component和靜態工廠方法
- 9. 靜態工廠方法查詢
- 10. 繼承和靜態工廠方法
- 11. 靜態接口工廠方法[Java 8]
- 12. 靜態工廠方法問題!
- 13. Java 8接口 - 靜態工廠方法
- 14. EJB的靜態工廠方法
- 15. 使用枚舉作爲工廠vs靜態工廠方法
- 16. 靜態工廠方法和靜態對象的內存泄漏
- 17. 如何使靜態工廠方法不是靜態實例?
- 18. 內部工廠的靜態工廠方法網關 - 代碼異味?
- 19. Java的泛型和靜態工廠方法 - 語法
- 20. 通用靜態工廠
- 21. 工廠方法:靜態函數VS C++中的非靜態函數實現
- 22. 非靜態方法尋呼機::廠()不應該叫靜態
- 23. 靜態和非靜態方法工作
- 24. 如何用靜態工廠方法創建抽象類?
- 25. 靜態工廠避免重複對象的方法
- 26. 從靜態類工廠方法中獲取屬性
- 27. 使用靜態方法的輔助類的工廠?
- 28. 在靜態工廠方法中分配事件處理委託
- 29. 的Java:靜態工廠方法和線程安全
- 30. 如何通過靜態工廠方法返回對象?
這裏有一個單一的工廠方法的優勢是什麼d返回父類和子類的對象。如果我想要一個父類型對象變量來保存子類類型的對象,我可以有一個子類的構造函數生成它有什麼害處。我不明白這將是一個怎樣的有用的事情。 –
@ david.colais這個鏈接有一個很長的名單,解釋各種好處:http://my.safaribooksonline.com/book/programming/java/9780137150021/creating-and-destroying-objects/ch02lev1sec1 –