Design Pattern - Factory

less than 1 minute read

Tables

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.

Factory pattern class diagram

factory-design-pattern

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.equals("boy")){
			p = new Boy();
		}else if(m.equals("girl")){
			p = new Girl();
		}
 
		return p;
	}
}

References

Leave a Comment