简体   繁体   English

静态工厂方法

[英]Static Factories Methods

One advantage of static factories method states that: 静态工厂方法的优点之一是:

Unlike constructors they can return an object of any subtype of their return type which gives you great flexibility in choosing the class of returned object. 与构造函数不同,它们可以返回其返回类型的任何子类型的对象,这使您在选择返回对象的类时具有极大的灵活性。

What does this mean exactly? 这到底是什么意思? Can someone explain this with code? 有人可以用代码解释吗?

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

Let me break your question in two parts 让我将您的问题分为两个部分
(1) Unlike constructors they can return an object of any subtype of their return type (1)与构造函数不同,它们可以返回其返回类型的任何子类型的对象
(2) which gives you great flexibility in choosing the class of returned object. (2)这使您在选择返回对象的类时具有极大的灵活性。
Let say You have two classes Extended from Player which are PlayerWithBall and PlayerWithoutBall 假设您有两个从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();

Here you get the both answers Flexability and unlike constructor behaviour Now You can see through these factory methods its upto you that WHICH TYPE OF PLAYER YOU NEED 在这里,您将获得两个答案: 灵活性不同于构造函数的行为。现在,您可以通过这些工厂方法来了解所需的播放器类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM