Clark To Do The blog of Clark

Java设计模式:工厂

注:本文为译文,原文出处java-design-patterns-in-stories

1. 工厂模式的故事

工厂模式被用于基于不同参数来创建对象. 下面是一个通过工厂造人的例子. 如果我们向工厂要一个男孩, 他就会生成一个男孩, 反之亦然. 基于不同的参数, 工厂会生产出不同的事物.

2. 工厂模式类图

factory-design-pattern

3. 工厂模式Java代码

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;
  }
}

4. 工厂模式在Java standard library中的应用

基于不同参数, 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)
comments powered by Disqus