Factory Design Pattern Tutorial

Factory Design Pattern TutorialWelcome to my Factory design pattern tutorial. This is a continuation of my design patterns video tutorial.

You use the Factory design pattern when you want to define the class of an object at runtime. It also allows you to encapsulate object creation so that you can keep all object creation code in one place.

The Factory pattern is presented in many ways to help you learn. Refer to the code that follows the video to completely understand it.

If you like videos like this, please tell google

Sharing is nice

Code from the Video

ENEMYSHIP.JAVA

public abstract class EnemyShip {
	
	private String name;
	private double speed;
	private double directionX;
	private double directionY;
	private double amtDamage;
	
	public String getName() { return name; }
	public void setName(String newName) { name = newName; }
	
	public double getDamage() { return amtDamage; }
	public void setDamage(double newDamage) { amtDamage = newDamage; }
	
	public void followHeroShip(){
		
		System.out.println(getName() + " is following the hero");
		
	}
	
	public void displayEnemyShip(){
		
		System.out.println(getName() + " is on the screen");
		
	}
	
	public void enemyShipShoots() {
		
		System.out.println(getName() + " attacks and does " + getDamage() + " damage to hero");
		
	}
	
}

UFOENEMYSHIP.JAVA

public class UFOEnemyShip extends EnemyShip {
	
	public UFOEnemyShip(){
		
		setName("UFO Enemy Ship");
		
		setDamage(20.0);
		
	}
	
}

ROCKETENEMYSHIP.JAVA

public class RocketEnemyShip extends EnemyShip {
	
	public RocketEnemyShip(){
		
		setName("Rocket Enemy Ship");
		
		setDamage(10.0);
		
	}
	
}

ENEMYSHIPTESTING.JAVA

import java.util.Scanner;

public class EnemyShipTesting {

	public static void main(String[] args){
		
		// Create the factory object
		EnemyShipFactory shipFactory = new EnemyShipFactory();
		
		// Enemy ship object
		
		EnemyShip theEnemy = null;
		
		Scanner userInput = new Scanner(System.in);
		
		System.out.print("What type of ship? (U / R / B)");
		
		if (userInput.hasNextLine()){
			
			String typeOfShip = userInput.nextLine();
		
			theEnemy = shipFactory.makeEnemyShip(typeOfShip);
			
			if(theEnemy != null){
				
				doStuffEnemy(theEnemy);
				
			} else System.out.print("Please enter U, R, or B next time");
		
		}
		
		/*
		EnemyShip theEnemy = null;
		
		// Old way of creating objects
		// When we use new we are not being dynamic
		
		EnemyShip ufoShip = new UFOEnemyShip();
		
		doStuffEnemy(ufoShip);
		
		System.out.print("\n");
		
		// -----------------------------------------
		
		// This allows me to make the program more dynamic
		// It doesn't close the code from being modified
		// and that is bad!
		
		// Defines an input stream to watch: keyboard
		Scanner userInput = new Scanner(System.in);
		
		String enemyShipOption = "";
		
		System.out.print("What type of ship? (U or R)");
		
		if (userInput.hasNextLine()){
			
			enemyShipOption = userInput.nextLine();
			
		}
		
		if (enemyShipOption == "U"){
			
			theEnemy = new UFOEnemyShip();

			
		} else 
		
		if (enemyShipOption == "R"){
			
			theEnemy = new RocketEnemyShip();
			
		} else {
			
			theEnemy = new BigUFOEnemyShip();
			
		}
		
		doStuffEnemy(theEnemy);
		
		// --------------------------------------------
		*/
		
	}
	
	// Executes methods of the super class
	
	public static void doStuffEnemy(EnemyShip anEnemyShip){
		
		anEnemyShip.displayEnemyShip();
		
		anEnemyShip.followHeroShip();
		
		anEnemyShip.enemyShipShoots();
		
	}
	
}

BIGUFOENEMYSHIP.JAVA

public class BigUFOEnemyShip extends UFOEnemyShip {
	
	public BigUFOEnemyShip(){
		
		setName("Big UFO Enemy Ship");
		
		setDamage(40.0);
		
	}
	
}

ENEMYSHIPFACTORY.JAVA

// This is a factory thats only job is creating ships
// By encapsulating ship creation, we only have one
// place to make modifications

public class EnemyShipFactory{
	
	// This could be used as a static method if we
	// are willing to give up subclassing it
	
	public EnemyShip makeEnemyShip(String newShipType){
		
		EnemyShip newShip = null;
		
		if (newShipType.equals("U")){
			
			return new UFOEnemyShip();
			
		} else 
		
		if (newShipType.equals("R")){
			
			return new RocketEnemyShip();
			
		} else 
		
		if (newShipType.equals("B")){
			
			return new BigUFOEnemyShip();
			
		} else return null;
		
	}
	
}

Factory Design Pattern Diagram

Factory Design Pattern

37 Responses to “Factory Design Pattern Tutorial”

  1. Faisal says:

    Hi Derek, many many thanks for all these awesome video tutorials on Design Patterns. Just wondering why not also you provide the Alien Spaceship diagrams related to individual Tutorial?

    Those will be really helpful. Thanks once again.

  2. pere says:

    hi this is really great and helpful. Thx for the dedication.
    1 question though, in ENEMYSHIPFACTORY.JAVA class, why do u need line 12: EnemyShip newShip = null;
    i don’t see you use this local variable?

    thx

  3. Hi Derek. Thank you so much for the tutorial. I have started to learn your tutorials on Design Patterns. Though I have not learned Java, I am able to follow your code. I know C++. So what I do is after going through your tutorial, I implement the code example for the design pattern in C++. Oh My! I am learning a lot.

    Now coming to your tutorial on Factory Design Pattern. I have tried very hard to get a solid understanding on this design pattern for quite some time now. But I never succeeded. At last your tutorial provided me much needed succor and it took just 11 minutes to understand the entire thing. Thank you so much for this, Derek. I am a big fan of yours. As always you are always succinct with your tutorials.

  4. Anil says:

    Line 12 EnemyShipTesting.java

    EnemyShip theEnemy = null;

    Since EnemyShip class is abstract, How can we create objects of the same?

    • Derek Banas says:

      We are actually calling the constructor for either UFOEnemyShip or RocketEnemyShip. In the above I’m declaring that I will use EnemyShip to refer to data and nothing else since it isn’t a primitive. Later when I call the constructors mentioned actually creates an object. Does that make sense?

  5. Khalid says:

    Hi Derek,

    Thank you so much for all the work you put into your tutorials, having been a software developer in Java for 12 years I can honestly say I’ve learnt more from your site than at work!

    Believe me it’s frustrating beyond belief trying to code blind not knowing how things fit together and not knowing where to go!

    My question is related to why the EnemyShip class is abstract, is the idea of the pattern to have it abstract? The reason I ask is that the class has concrete implementations so it could be just as well a concrete class?

    • Derek Banas says:

      Thank you very much for taking the time to write such a nice message 🙂

      I’m very happy to have been able to help.

      I basically made it abstract because there is no reason to instantiate EnemyShip. That is basically the only reason.

  6. Anirban says:

    Derek your videos are extremely helpful, just a small suggestion, while organizing the classes, please group them together in a way that makes the code more readable. For example while reading from top down I would like to read UFOEnemyShip, rocketShip and BigUFOEnemyShip together, then the EnemyShipFactory and finally the class containing the main method.

  7. G1 says:

    Your videos are clear, precise, straight and has lot of information. Thank you.

  8. Jessica Huang says:

    hello, derek
    once again, thanks for the great tutorial
    I have a question: what is the purpose of making the EnemyShip class abstract? since there are no abstract methods, or final or static fields inside the EnemyShip, I guess it is to make this class not to be instantiated, but if so, why do it that way?
    thanks you very much(as always:-))

  9. Fong says:

    Hi Derek,

    First of all, thank you very much for another excellent tutorial.

    My question is, in EnemyShipFactory.java. You are using if statements here. I remember you have a refactor tutorial about this. In there, you used switch (same as if) first and then used reflection. I think that you were required not to use any if or switch statements in a coding challenge.

    What is the best practice to create ships when applying Factory Method design pattern?

    Thanks,
    Fong

    • Derek Banas says:

      Hi Fong,

      You’re very welcome 🙂 Thank you for visiting my site.

      It changes depending on the situation. I know as programmers we start off learning a ton of rules. In the beginning there is always a right and wrong way of doing things. That pretty much ends once you get advanced and start using things like design patterns and when you refactor.

      You learn when to use these things through a ton of experimenting. It is more art then science at this point. Even the GOF design pattern book says as much. Now is when you truly become an advanced programmer. Enjoy the journey.

      Sorry I couldn’t give a more definite answer, but this is truly what i believe. I hope that helps
      Derek

  10. Kitty says:

    Hi Derek,

    Thank you very much for video.
    All design pattern concepts are very nicely presented with exeample .
    Just I have a request, is there any place where I can download
    all code(zip, jar..) ?

    Do you have videos of webservices (CXF) ?

    Thnaks and Best Regards,
    Kitty

  11. Ramesh says:

    Hello Sir,
    One question, in a scenario where one factory to produce multiple products.
    In this case, Factory class job to produce EnemyShip as well as HeroShip (multiple products). Then to accommodate this requirement I guess we need to have another method makeHeroShip() with return type HeroShip in the same Factory class (suppose ShipFactory). am I right? Or there is more better way to achieve this. Please share your views.

  12. Eric Black says:

    I don’t need a college degree. I just need DEREK BANAS! Awesome tutorials dude. I am going to Donate five bucks. I will donate more when I can. I have been watching your tutorials everynight and I’m enjoying them very much. Thanks! Eric.

  13. Shahad says:

    Big thanks to you
    I have exams next week and your videos really helped me.
    best of luck for you

  14. Stuart says:

    Hey Derek, a big thank you all the way from Scotland, your video’s have been a great help.

  15. Mark Z says:

    Thanks so much!

  16. Mina says:

    Thank you very much, these videos are really helpful for me.

  17. Tilak says:

    Hi Derek,
    Thanks for this video. It helps in understanding factory pattern with ease in short time.

    Can you also list down cons of factory pattern, complexity introduced by factory pattern, and other pattern that can be used as alternative.

    Thanks.

    • Derek Banas says:

      Hi, You may find that dependency injection is often a better option over the factory pattern. We use factory to separate the use of a component from the implementation and instance management of that component. The major drawback of the factory versus dependency injection is that it can be complex and hard to test.

  18. Mike says:

    I was curious what you used to create the UML diagrams in your videos?

Leave a Reply

Your email address will not be published.

Google+