静态工厂方法

dav*_*ais 4 java

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

与构造函数不同,它们可以返回其返回类型的任何子类型的对象,这使您在选择返回对象的类时具有很大的灵活性.

这究竟是什么意思?有人能用代码解释一下吗?

Cor*_*all 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.
    }
}
Run Code Online (Sandbox Code Playgroud)