A brief about Factory Method Design Pattern

Posted By : Mohit Shakya | 31-Mar-2018

In this blog, we'll get to know about 'Factory Method Design Pattern', a well known Software Design Pattern for 'class-based programming'.

We'll be covering following points in this:

  • Why we should use Facade Design Pattern
  • How to implement Facade Design Pattern ( An Example )

 

Why should we use Facade Design Pattern?

Factory method design pattern is basically used when we've to solve recurring design problems to design a flexible and reusable source code, that means you can easily use them, modify them or test them.

This pattern solves following type problems:

  • Creation of object in such a way that subclass should be able to redefine which class to instantiate.
  • Object creation by calling a factory method of the main interface where factory method will be responsible for instantiation to new class object.

 

How to implement Factory Method Pattern?

Please consider following the example of planes for factory method pattern.

 

abstract class Plane{			// class for planes common functionalities
	protected abstract String getCodeName();
}

public class JetPlane extends Plane{	// specific to JetPlane configuration
	@Override
	protected String getCodeName(){
		return 'Jet';
	}
}

public class CargoPlane extends Plane{ // specific to cargo plane configuration
	@Override
	protected String getCodeName(){
		return 'Cargo';
	}
}

public abstract class PlaneFactory{ // common class for default factory configuration for all planes
	public Plane getPlane(){
		return makePlane();
	}
	
	protected abstract Plane makePlane();
}

public class JetPlaneFactory extends PlaneFactory { // JetPlaneFactory extends to default functionalities and fulfills remaining.
	@Override
	protected Plane makePlane(){
		return new JetPlane();
	}
}

public class CargoPlaneFactory extends PlaneFactory { // CargoPlaneFactory extends to default functionalities and fulfills remaining.
	@Override
	protected Plane makePlane(){
		return new CargoPlane();
	}
}

class Main {
	public static void main (String[] args) {
		PlaneFactory factory = new JetPlaneFactory();
		Plane model1 = factory.getPlane();
		
		factory = new CargoPlaneFactory();
		Plane model2 = factory.getPlane();
		
		System.out.println("Model Name: "+model1.getCodeName());
		System.out.println("Model Name: "+model2.getCodeName());
	}
}


output:

Model Name: Jet
Model Name: Cargo

In above example 'makePlane()' was a factory method that was responsible to instantiate the new object for other classes.

I hope this brief introduction of 'Factory Method Pattern' will be helpful.

About Author

Author Image
Mohit Shakya

Mohit has worked in groovy and grails, filesystems, ffmpeg. Mohit likes to be adventurous, likes music, solving puzzles, playing chess, and basketball.

Request for Proposal

Name is required

Comment is required

Sending message..