簡體   English   中英

靜態工廠方法

[英]Static Factories Methods

靜態工廠方法的優點之一是:

與構造函數不同,它們可以返回其返回類型的任何子類型的對象,這使您在選擇返回對象的類時具有極大的靈活性。

這到底是什么意思? 有人可以用代碼解釋嗎?

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)與構造函數不同,它們可以返回其返回類型的任何子類型的對象
(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();

在這里,您將獲得兩個答案: 靈活性不同於構造函數的行為。現在,您可以通過這些工廠方法來了解所需的播放器類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM