Probably one of the most frequently used creational patterns, a Factory is a class which produces objects for clients usage.

Intent

Here is a sample factory:

    class WaspFactory{
    	public static Wasp createWasp(){
    		// However you'd like to create a wasp.
    	}
    }

Then you can create a wasp by simply calling WaspFactory.createWasp(); from the client. The good thing about this pattern is that with a little bit of imagination, you can create various factories abstract factories which may serve you well in terms of maintenance.

Here is an example of how. Say we have a WaspFactory interface.

    
    // Wasp.java
    public interface Wasp {
    	// Wasp Interface
    }
    
    // Hornet.java
    class Hornet implements Wasp {
    	protected Hornet(){
    		System.out.println("Hornet created.");
    	}
    }
    
    // PollenWasp.java
    public class PollenWasp implements Wasp {
    	protected PollenWasp(){
    		System.out.println("Pollen Wasp created.");
    	}
    }

Above you may see the implementations of Wasp interface. Pay attention to keyword protected at definition of constructors. This behaviour enforces that only a class in the exact same package can create a Hornet or a PollenWasp. Now lets create the factory that will create these wasps.

    public class WaspFactory{
    
    	public enum WaspType{
    		HORNET,POLLEN_WASP
    	}
    	
    	private static WaspFactory instance;
    	
    	private WaspFactory(){
    	}
    	
    	public static WaspFactory getInstance(){
    		if(instance == null)
    			return new WaspFactory();
    		else
    			return instance;
    	}
    	
    	public Wasp createWasp(WaspType type){
    		switch(type){
    		case HORNET:
    			return new Hornet();
    		case POLLEN_WASP:
    			return new PollenWasp();
    		default:
    			return null;
    		}
    	}
    }

Above you can see the WaspFactory as a Singleton with an enumeration of wasp types to pick. Creating this class in same package will let the factory to create these wasps while encapsulating them from rest. Now lets see the usage of this code.

	WaspFactory wf = WaspFactory.getInstance(); 
	wf.createWasp(WaspFactory.WaspType.HORNET);		// Hornet created.
	wf.createWasp(WaspFactory.WaspType.POLLEN_WASP);	//Pollen Wasp created.