Static Plant Methods

One of the advantages of the static factory method is that:

Unlike constructors, they can return an object of any subtype of the return type, which gives you more flexibility when choosing the class of the return object.

What does it mean? Can someone explain this with code?

+4
source share
2 answers
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. } } 
+5
source

Let me split 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 when choosing the class of the returned object.
Let them say that you have two Extended classes 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 both answers. Flexibility and as opposed to constructor behavior. Now you can see with these factory methods that you must do WHAT PLAYER TYPE YOU NEED

+1
source

Source: https://habr.com/ru/post/1447651/


All Articles