2012-11-22 123 views
4

靜態工廠方法的一個優點指出:靜態工廠方法

構造不同,他們可以回到他們的返回類型的任何亞型,讓你在選擇類返回對象的極大靈活性的對象。

這是什麼意思? 有人可以解釋這與代碼?

回答

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. 
    } 
} 
+0

這裏有一個單一的工廠方法的優勢是什麼d返回父類和子類的對象。如果我想要一個父類型對象變量來保存子類類型的對象,我可以有一個子類的構造函數生成它有什麼害處。我不明白這將是一個怎樣的有用的事情。 –

+0

@ david.colais這個鏈接有一個很長的名單,解釋各種好處:http://my.safaribooksonline.com/book/programming/java/9780137150021/creating-and-destroying-objects/ch02lev1sec1 –

1

讓我打破你的問題分兩部分
(1)與構造,他們可以回到他們的返回類型的任何亞型的對象
(2),讓你在選擇了極大的靈活性返回對象的類。
比方說您已經從Player這是PlayerWithBallPlayerWithoutBall

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不像構造行爲 現在你可以看到通過這些工廠方法它取決於你,你需要哪種類型的球員