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();
静态工厂方法模式是一种封装对象创建的方法。如果没有工厂方法,你只需直接调用类的构造函数: Foo x = new Foo()。使用这种模式,你可以调用工厂方法:Foo x = Foo.create()。构造函数被标记为private,因此只能从类内部调用它们,而工厂方法被标记为static,以便可以在没有对象的情况下调用它。
我想我会在这篇文章中添加一些我所知道的东西。我们在recent android project中广泛使用了这个技巧。除了creating objects using new operator,你还可以使用static method来实例化一个类。代码清单:
//instantiating a class using constructor
Vinoth vin = new Vinoth();
//instantiating the class using static method
Class Vinoth{
private Vinoth(){
}
// factory method to instantiate the class
public static Vinoth getInstance(){
if(someCondition)
return new Vinoth();
}
}
public class Singleton{
//initailzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}