注:本文为译文,原文出处java-design-patterns-in-stories
工厂模式被用于基于不同参数来创建对象. 下面是一个通过工厂造人的例子. 如果我们向工厂要一个男孩, 他就会生成一个男孩, 反之亦然. 基于不同的参数, 工厂会生产出不同的事物.
interface Human {
public void Talk();
public void Walk();
}
class Boy implements Human{
@Override
public void Talk() {
System.out.println("Boy is talking...");
}
@Override
public void Walk() {
System.out.println("Boy is walking...");
}
}
class Girl implements Human{
@Override
public void Talk() {
System.out.println("Girl is talking...");
}
@Override
public void Walk() {
System.out.println("Girl is walking...");
}
}
public class HumanFactory {
public static Human createHuman(String m){
Human p = null;
if(m == "boy"){
p = new Boy();
}else if(m == "girl"){
p = new Girl();
}
return p;
}
}
基于不同参数, getInstance()方法返回不同的Calendar的实例.
java.util.Calendar - getInstance()
java.util.Calendar - getInstance(TimeZone zone)
java.util.Calendar - getInstance(Locale aLocale)
java.util.Calendar - getInstance(TimeZone zone, Locale aLocale)
java.text.NumberFormat - getInstance()
java.text.NumberFormat - getInstance(Locale inLocale)