Welcome 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
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.
Do you want to see the UML diagrams I made? I can upload them if I still have them
Yes Derek, something like what you have for “Abstract Factory Design Pattern Diagram” (at the very bottom of that article)
Thanks
I’ll see if I can find all of those. Thanks for pointing that out. I don’t know what works most of the time and what doesn’t
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
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.
Thank you very much for taking the time to write such a nice comment. I very much appreciate it! I’m very happy that I’ve been able to help you 🙂
Line 12 EnemyShipTesting.java
EnemyShip theEnemy = null;
Since EnemyShip class is abstract, How can we create objects of the same?
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?
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?
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.
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.
Thank you 🙂 Sorry if that was confusing. I’m constantly working to make everything understandable. Thank you for the input
Your videos are clear, precise, straight and has lot of information. Thank you.
You’re very welcome 🙂 Thank you
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:-))
Thank you 🙂 Yes the only reason is to keep the EnemyShip from being instantiated. In this situation that is the only goal. Sorry about any confusion
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
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
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
Hi Kitty,
You’re very welcome 🙂 Sorry, but I don’t have them all in one zipped file because that would be quite confusing because there are so many files. I do however have everything on one page here Design Pattern Video Tutorial.
I plan on cover web services and J2EE soon. Thank you 🙂 Derek
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.
Hello, It may be best to see more examples of the factory pattern. I have 2 additional videos on this refactoring tutorial page. I hope that helps 🙂
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.
Thank you 🙂 The compliment is all I ask for. There is no reason to donate. That is there only because my wife forced me to use it.
Big thanks to you
I have exams next week and your videos really helped me.
best of luck for you
Thank you 🙂 I’m glad I could help. Best of luck on your exams.
Hey Derek, a big thank you all the way from Scotland, your video’s have been a great help.
Hey Stuart, I will always be amazed that people all over the world are watching my videos! You’re very welcome 🙂
Thanks so much!
You’re very welcome 🙂
Thank you very much, these videos are really helpful for me.
You’re very welcome 🙂 I’m glad they are helping so many people.
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.
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.
I was curious what you used to create the UML diagrams in your videos?
Normally just paper and pencil. UMLet is nice though if I need it. Visual Paradigm is the best program, but expensive.