简体   繁体   中英

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
(2) which gives you great flexibility in choosing the class of returned object.
Let say You have two classes Extended from Player which are PlayerWithBall and 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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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