首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >静态工厂法

静态工厂法
EN

Stack Overflow用户
提问于 2012-11-22 04:49:43
回答 2查看 120关注 0票数 4

静态工厂方法的一个优点是:

与构造函数不同,它们可以返回返回类型的任何子类型的对象,这为您选择返回对象的类提供了很大的灵活性。

这到底是什么意思?有人能用密码解释这件事吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-22 04:54:23

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-11-22 05:06:13

让我把你的问题分成两部分

(1)与构造函数不同,它们可以返回返回类型的任何子类型的对象

(2)这为您选择返回对象的类提供了很大的灵活性。

假设您有两个从Player扩展出来的类,即PlayerWithBallPlayerWithoutBall

代码语言:javascript
复制
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();

在这里您可以得到两个答案:Flexability,并且与构造函数行为不同,现在您可以通过这些工厂方法看到,这取决于您需要哪种类型的播放器

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13506073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档