静态工厂方法的一个优点是:
与构造函数不同,它们可以返回其返回类型的任何子类型的对象,这使您在选择返回对象的类时具有很大的灵活性。
这究竟是什么意思? 有人可以用代码解释这个吗?
答案 0 :(得分: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.
}
}
答案 1 :(得分:1)
让我分两部分来解决你的问题
(1)与构造函数不同,它们可以返回其返回类型的任何子类型的对象
(2),这使您在选择返回对象的类时具有很大的灵活性。
假设您有Player
个PlayerWithBall
和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();
在这里,你得到了两个答案 灵活性和不像构造函数行为 现在你可以通过这些工厂方法看到你需要哪种类型的玩家