Java Design Pattern: Factory

2013/10/26 18:31
阅读数 46

1. The story for Factory pattern

Factory design pattern is used for creating an object based on different parameters. The example below is about creating human in a factory. If we ask the factory for a boy, the factory will produce a boy; if we ask for a girl, the factory will produce a girl. Based on different parameters, the factory produce different stuff.

2. Factory pattern class diagram

factory-design-pattern

3. Factory pattern Java code

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. Factory design pattern used in Java standard library

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)

A simple example of Calendar.getInstance():

public static String getCurrentTime(){
  Calendar c=Calendar.getInstance();
  String hour="" + c.get(Calendar.HOUR_OF_DAY);
  String min="" + c.get(Calendar.MINUTE);
  String sec="" + c.get(Calendar.SECOND);
  if (hour.length() == 1)   hour="0" + hour;
  if (min.length() == 1)   min="0" + min;
  if (sec.length() == 1)   sec="0" + sec;
  return hour + ":" + min+ ":"+ sec;
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部