为什么要在JAVA工厂模式中使用静态方法
作者:网络转载 发布时间:[ 2012/12/19 9:42:55 ] 推荐标签:
多个工厂方法也可以允许对相似参数类型的不同解析。通常构造方法有与类相同的名字,这意味着如果给定一个签名(signature)你只能拥有一个构造方法。工厂模式则没有这么多的限制。也是说你可以有不同的方法但是却接收相同的参数类型:
Coordinate c = Coordinate.createFromCartesian(double x, double y)
Coordinate c = Coordinate.createFromPolar(double distance, double angle)
这可以用来提高代码的可读性。
比较下面的两种不同方式:
public class Foo{
public Foo(boolean withBar){
//...
}
}
//...
// What exactly does this mean?
Foo foo = new Foo(true);
// You have to lookup the documentation to be sure.
// Even if you remember that the boolean has something to do with a Bar
// you might not remember whether it specified withBar or withoutBar.
public class Foo{
public static Foo createWithBar(){
//...
}
public static Foo createWithoutBar(){
//...
}
}
// ...
// This is much easier to read!
Foo foo = Foo.createWithBar();

sales@spasvo.com