Here is my Abstract Factory design pattern tutorial. I also take a second look at the Factory design pattern here as well.
This is considered a hard pattern to understand, but I consider it to be a combination of all you have learned previously. You just need to understand that each step is separated by either a abstract class or an interface. This makes it possible to make extremely flexible objects.
All of the code follows the video and is heavily commented.
If you like videos like this, it helps if you tell Google by clicking here [googleplusone]
Sharing is nice
If you want the Alien Spaceship diagram, it as at the bottom of the page.
Code from the Video
EnemyShipTesting.java
public class EnemyShipTesting { public static void main(String[] args) { // EnemyShipBuilding handles orders for new EnemyShips // You send it a code using the orderTheShip method & // it sends the order to the right factory for creation EnemyShipBuilding MakeUFOs = new UFOEnemyShipBuilding(); EnemyShip theGrunt = MakeUFOs.orderTheShip("UFO"); System.out.println(theGrunt + "\n"); EnemyShip theBoss = MakeUFOs.orderTheShip("UFO BOSS"); System.out.println(theBoss + "\n"); } }
EnemyShipBuilding.java
public abstract class EnemyShipBuilding { // This acts as an ordering mechanism for creating // EnemyShips that have a weapon, engine & name // & nothing else // The specific parts used for engine & weapon depend // upon the String that is passed to this method protected abstract EnemyShip makeEnemyShip(String typeOfShip); // When called a new EnemyShip is made. The specific parts // are based on the String entered. After the ship is made // we execute multiple methods in the EnemyShip Object public EnemyShip orderTheShip(String typeOfShip) { EnemyShip theEnemyShip = makeEnemyShip(typeOfShip); theEnemyShip.makeShip(); theEnemyShip.displayEnemyShip(); theEnemyShip.followHeroShip(); theEnemyShip.enemyShipShoots(); return theEnemyShip; } }
UFOEnemyShipBuilding.java
// This is the only class that needs to change, if you // want to determine which enemy ships you want to // provide as an option to build public class UFOEnemyShipBuilding extends EnemyShipBuilding { protected EnemyShip makeEnemyShip(String typeOfShip) { EnemyShip theEnemyShip = null; // If UFO was sent grab use the factory that knows // what types of weapons and engines a regular UFO // needs. The EnemyShip object is returned & given a name if(typeOfShip.equals("UFO")){ EnemyShipFactory shipPartsFactory = new UFOEnemyShipFactory(); theEnemyShip = new UFOEnemyShip(shipPartsFactory); theEnemyShip.setName("UFO Grunt Ship"); } else // If UFO BOSS was sent grab use the factory that knows // what types of weapons and engines a Boss UFO // needs. The EnemyShip object is returned & given a name if(typeOfShip.equals("UFO BOSS")){ EnemyShipFactory shipPartsFactory = new UFOBossEnemyShipFactory(); theEnemyShip = new UFOBossEnemyShip(shipPartsFactory); theEnemyShip.setName("UFO Boss Ship"); } return theEnemyShip; } }
EnemyShipFactory.java
// With an Abstract Factory Pattern you won't // just build ships, but also all of the components // for the ships // Here is where you define the parts that are required // if an object wants to be an enemy ship public interface EnemyShipFactory{ public ESWeapon addESGun(); public ESEngine addESEngine(); }
UFOEnemyShipFactory.java
// This factory uses the EnemyShipFactory interface // to create very specific UFO Enemy Ship // This is where we define all of the parts the ship // will use by defining the methods implemented // being ESWeapon and ESEngine // The returned object specifies a specific weapon & engine public class UFOEnemyShipFactory implements EnemyShipFactory{ // Defines the weapon object to associate with the ship public ESWeapon addESGun() { return new ESUFOGun(); // Specific to regular UFO } // Defines the engine object to associate with the ship public ESEngine addESEngine() { return new ESUFOEngine(); // Specific to regular UFO } }
UFOBossEnemyShipFactory.java
// This factory uses the EnemyShipFactory interface // to create very specific UFO Enemy Ship // This is where we define all of the parts the ship // will use by defining the methods implemented // being ESWeapon and ESEngine // The returned object specifies a specific weapon & engine public class UFOBossEnemyShipFactory implements EnemyShipFactory{ // Defines the weapon object to associate with the ship public ESWeapon addESGun() { return new ESUFOBossGun(); // Specific to Boss UFO } // Defines the engine object to associate with the ship public ESEngine addESEngine() { return new ESUFOBossEngine(); // Specific to Boss UFO } }
EnemyShip.java
public abstract class EnemyShip { private String name; // Newly defined objects that represent weapon & engine // These can be changed easily by assigning new parts // in UFOEnemyShipFactory or UFOBossEnemyShipFactory ESWeapon weapon; ESEngine engine; public String getName() { return name; } public void setName(String newName) { name = newName; } abstract void makeShip(); // Because I defined the toString method in engine // when it is printed the String defined in toString goes // on the screen public void followHeroShip(){ System.out.println(getName() + " is following the hero at " + engine ); } public void displayEnemyShip(){ System.out.println(getName() + " is on the screen"); } public void enemyShipShoots(){ System.out.println(getName() + " attacks and does " + weapon); } // If any EnemyShip object is printed to screen this shows up public String toString(){ String infoOnShip = "The " + name + " has a top speed of " + engine + " and an attack power of " + weapon; return infoOnShip; } }
UFOEnemyShip.java
public class UFOEnemyShip extends EnemyShip{ // We define the type of ship we want to create // by stating we want to use the factory that // makes enemy ships EnemyShipFactory shipFactory; // The enemy ship required parts list is sent to // this method. They state that the enemy ship // must have a weapon and engine assigned. That // object also states the specific parts needed // to make a regular UFO versus a Boss UFO public UFOEnemyShip(EnemyShipFactory shipFactory){ this.shipFactory = shipFactory; } // EnemyShipBuilding calls this method to build a // specific UFOEnemyShip void makeShip() { System.out.println("Making enemy ship " + getName()); // The specific weapon & engine needed were passed in // shipFactory. We are assigning those specific part // objects to the UFOEnemyShip here weapon = shipFactory.addESGun(); engine = shipFactory.addESEngine(); } }
UFOBossEnemyShip.java
public class UFOBossEnemyShip extends EnemyShip{ // We define the type of ship we want to create // by stating we want to use the factory that // makes enemy ships EnemyShipFactory shipFactory; // The enemy ship required parts list is sent to // this method. They state that the enemy ship // must have a weapon and engine assigned. That // object also states the specific parts needed // to make a Boss UFO versus a Regular UFO public UFOBossEnemyShip(EnemyShipFactory shipFactory){ this.shipFactory = shipFactory; } // EnemyShipBuilding calls this method to build a // specific UFOBossEnemyShip void makeShip() { // TODO Auto-generated method stub System.out.println("Making enemy ship " + getName()); // The specific weapon & engine needed were passed in // shipFactory. We are assigning those specific part // objects to the UFOBossEnemyShip here weapon = shipFactory.addESGun(); engine = shipFactory.addESEngine(); } }
ESEngine.java
// Any part that implements the interface ESEngine // can replace that part in any ship public interface ESEngine{ // User is forced to implement this method // It outputs the string returned when the // object is printed public String toString(); }
ESWeapon.java
// Any part that implements the interface ESWeapon // can replace that part in any ship public interface ESWeapon{ // User is forced to implement this method // It outputs the string returned when the // object is printed public String toString(); }
ESUFOGun.java
// Here we define a basic component of a space ship // Any part that implements the interface ESWeapon // can replace that part in any ship public class ESUFOGun implements ESWeapon{ // EnemyShip contains a reference to the object // ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed // the following shows on the screen public String toString(){ return "20 damage"; } }
ESUFOEngine.java
// Here we define a basic component of a space ship // Any part that implements the interface ESEngine // can replace that part in any ship public class ESUFOEngine implements ESEngine{ // EnemyShip contains a reference to the object // ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed // the following shows on the screen public String toString(){ return "1000 mph"; } }
ESUFOBossGun.java
// Here we define a basic component of a space ship // Any part that implements the interface ESWeapon // can replace that part in any ship public class ESUFOBossGun implements ESWeapon{ // EnemyShip contains a reference to the object // ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed // the following shows on the screen public String toString(){ return "40 damage"; } }
ESUFOBossEngine.java
// Here we define a basic component of a space ship // Any part that implements the interface ESEngine // can replace that part in any ship public class ESUFOBossEngine implements ESEngine{ // EnemyShip contains a reference to the object // ESWeapon. It is stored in the field weapon // The Strategy design pattern is being used here // When the field that is of type ESUFOGun is printed // the following shows on the screen public String toString(){ return "2000 mph"; } }
Abstract Factory Design Pattern Diagram
Click on it, to see it full screen
is the whitepaper, UFO flow between the order/factory steps, available online?
thank you,
I have it up now. It is at the bottom of the page. Click on it to view full screen. The file is 1500px wide. Thanks for the request π
Thanks Derek for all the tutorials , but this one I am finding little difficult to grasp. The program flow are little long. May be , you can do similar kinds with shorter ones. Just a suggestion.
Thank you π I’ll revisit design patterns in my refactoring tutorial. Hopefully that will help. It requires a pretty solid understanding of OOD. Once you can completely understand objects you’ll get it. Don’t give up
Hi!! Thank you for all tutorials you did on DP!! R.E.S.P.E.C.T.
Is there any chance you can translate this Abstract Factory DP to UML notation, please??
I’m not sure how to UML this example. Thanks!
Regards,
J.
You’re very welcome π I’ll be making true uml diagrams for all of the patterns in the refactoring tutorial that is starting now. I’m not done with patterns and you can expect me to provide higher end tutorials now that I have covered them using very easy to understand diagrams. Thanks for the request
Author has keen knowledge on what is being delivered here. I started java programming and got good knowledge by going through your design pattern tutorials. It is worth time spending and applying those tricks in real world.
One small request is there a possibility to provide a zip file of all patterns code? That would be great help for all of us who are learning here. We can refer them as and when we face the challenges in future. I know we can always cut and paste but zip file would be great short cut:)
Thanks!
Hi, I’m glad you enjoyed the design patterns tutorials. I have to do some house keeping and will provide the pattern uml designs and the code in zipped format. I’ll be covering patterns as well in the refactoring tutorial. Thank you for the request
A big thanks to you Derek, I must say that you have an innate knowledge of the OOPS subject.
I thought that I knew it all, but after watching your tuts on YouTube(for now I have watched till Abstract Factory Pattern), I feel like a naive, though I was aware of Patterns; I never used them in my real coding ever, because I knew very little about how to put them to practice, but after watching those videos I am eager to implement them in my day to day programming at work and also in my self projects.
Thumbs up mate, thank you once again and please continue your effort on teaching me what I do not know.
Seriously you are doing a very good job, please keep it up.
Regards:
Arif Nadeem
Thank you Arif π Design patterns are something that you learn to use unlike most anything else in programming. I’m sure you remember the days in which OOP didn’t make sense. Soon design patterns will make sense just like you have learned to value OOP over procedural programming. Thank you for the nice comment! I do my best
Thank you for your excellent tutorials on design patterns. It might be a obvious to others but I have a question on the code presented above. UFOBossEnemyShip and UFOEnemyShip classes seem to have duplicated codes here. Is there any reason to have multiple classes on EnemyShip classes for this specific example?
They are similar, but they don’t have to be. I only made them similar so that I didn’t distract from the pattern. This is often considered to be a complex pattern, so I wanted to focus on the fact that the factory was just producing objects with attributes being the only thing that differs. I hope that helps
The ESUFOBossEngine.java code is not highlighting on this page.
Great tutorials!
Thanks.
Thank you π I’m not sure what problem you are having. Sometimes the page takes a few seconds to load. Sorry about the speed. I had to recently add a ton of security to the site and that is slowing things down a bit
The ESUFOBossEngine.java code in the web page:
the Java keywords are not highlighting (they are remaining black rather than blue). Also the return string is all black rather than blue.
I fixed it. Thanks for pointing that out π
Great job ! Your tutorials are very well explained and to the point !
Isn’t there a link on this page for downloading all the code in one .jar file ? It’s handier to navigate it on eclipse with the shortcuts.
Thank you π Ill add that to my to do list. I thought it might be confusing because I use file names that help people connect them to the proper video rather than to be descriptive. Sorry about that
Thanks you very much for the tutorial. I have read some book but I was not fully clear about the pattern. With this tutorial my pattern concepts getting stronger.
Thank you π I’m very happy to have been able to help
Great Tutorial i’ve ever seen =) Thx Derek for your effort.
I have just one question on abstract factory tutorial. Is that the reason this tutorial didn’t make fatories as singleton is because the next tutorial is singleton? Generally do we use singleton over here abstract factory as well? quite a bit difficult understand at once.
Thanks again for the great tutorial.
Thank you π You answered your own question. The reason I didn’t cover both at the same time is because I feel it is “difficult to understand both at once.” I cover the abstract factory again in Code Refactoring 18.
Thx again Derak=)
Now I am watching Flyweight Pattern. I am planing to go through all of your tutorial that i found very helpful!
You are very welcome π I’m very happy if I’m able to help on this topic
Hello Mr Derek!
First of all. Thank you so much for your videos. They are really great and I learn alot by just watching them.
I wonder if its possible to download the code as a zip file or project? I would be very gratefull if it was possible?
Thanks again.
/ Kalle
I mean all the codes for the design pattern series.
You’re very welcome π I’m sorry, but I’m not sure which files your looking for. I have all of the code on the site. If you want to get rid of the line numbers drift your mouse over the upper right edge of the code and click on the icon named View Source. I hope that helps
hello Derek, again thank you so much for the excellent tutorials. i also have the same request. yes, we can copy the files one at a time but they are so many. if for example the abstract factory design pattern had a zipped folder with all the java class files in it so that all code for this pattern could be downloaded at once, it would help so much. otherwise thanks for your time.
You’re very welcome π I’ll see what I can do about pulling them all together. They are all over the place right now. Sorry about that
thank you so much for your concern. π best regards
You’re very welcome π Thank you
Excellent tutorial.. Really helped me understand the patterns better and relate to it with real life examples.. Thanks once again..
You are very welcome π I’m very happy that it helped
thank you very much for your tutorials… all of them is very instructive π
You’re very welcome π I’m happy that you like them
Hello, I’m very glad I found this tutorial, without it I wouldn’t be making my own version of an abstract-factory to share it with my classmates on a presentation (next week). Thank you very much!!!
God bless you π
–>A colombian software engineering student.
Thank you very much π It is very gratifying to know I’m helping people all over the world. May god bless you and your loved ones as well!
thanks so so much Derek, for these excellent tutorials. My OOD skills have greatly improved. can’t thank you enough!!
cheers
… actually to introduce myself, I am a Ugandan (East African) Software Engineering student (Makerere University).. kr.
It is very gratifying to help people all over the world π Thank you
You’re very welcome π I’m very happy to help
Sir you are an awesome teacher! I am from Pakistan, learning and enjoying a lot from your tutorials sitting home! I will be getting a new skill just because of you!
Thankx alot and keep up the good work!
I find it amazing that people in Pakistan are watching my videos! I’m actually more popular outside of my country then I am in it. It is very nice to be able to help people all over the world. Thank you for taking the time to write the nice message π
So you have the tech. to create UFOs… huh? π
Thanks for great tutorials like these. As someone has already said above, you are helping us develop new skills. Many, many thanks for all this !
That’s funny π I definitely would love to cover electronics from the ground up. Then we could build anything!
I’m very happy that I have been able to help so many people.
the electronics stuff would be amazing!
this tutorial is amazing!
knowledge feels so awesome! thanks a million! π
You’re very welcome π I’ll see what I can do about the electronics video. I have been using Arduinos constantly lately, but I don’t know how to fit a tutorial on them into what I’ve been working on
What is the difference between the factory and abstract factory pattern? When to use which one? Thanks you’re the best I’m enjoying your video.
You basically use the abstract factory when you want another level of abstraction. It actually isn’t that common. I made another tutorial on the abstract factory that may clear it up.
Hi,
yours presentations are great, but this one makes me little embarrassed…
I think all plays in main() method.
If abstract factory returns concrete object, then it becomes just factory.
Instead it should return factory object . After that, you can easily construct objects which belongs to the Same Type.
In your example, it’s vary hard to get new object ‘ShipCaptain’ , with different values for types – UFO and UFOBOSS. To do it, you have to add another two ‘if’ in UFOEnemyShipBuilding.
Please try think that way:
IShipFactory=abstractFactory.getFactory(string typeOf); in example
IShip=IShipFactory.getShip();
ICaptain=IShipFactory.getCaptain();
Then, you have to make choice only once in abstractFactory which type of factory return.
All actions are moved to another level.
After that, you still can create ship type of ‘UfoBoss’ with different painting, for example.
your method (need another argument):
EnemyShip theBoss = MakeUFOs.orderTheShip(“UFO BOSS”,”Brown”);
my way:
IShip=IShipFactory.getShip(“Brown”);
And if you have one factory, when you creates another object , you are sure that all belongs to the same type family.
What do you think???
I think you have a very good idea and I’m glad that you came up with that and presented it here. I did my best to try and keep the example easy to understand above all else. I didn’t optimize the code to it’s best because of that. Thank you for the input.
Hi Drerk, at 3:20 min of this video, you said βwe are going to return an UFOEnemyShip which is abstract classβ. UFOEnemyShip is concrete class. Am I right or I am missing something?
Yes you are correct. I misspoke. I do these tutorials out of my head and sometimes I say the wrong thing. Sorry about that
Derek, you are da man!
One question though. Did you intentionally create UFOEnemyShip and UFOBossEnemyShip? It feels they do not have any meaning in this sample (their code is exactly the same too). It feels that just EnemyShip class would be enough for this sample: make it usual class, not abstract, move EnemyShipFactory property into it and make makeShip method defined in it as well. It would do exactly the same thing as all the specific details are encapsulated in factories and no specific details are in ships.
Or maybe I’m missing something here…
Anyway, this presentation rocks!
Thank you π Yes the abstract factory isn’t really required for something this simple. I used this example as you said just to keep the pattern simple and easier to understand.
Thanks you very much for your effort man,you are emazing man :)for sure every one who appreciate what mr Derek do have to donate even 5 dolla and me i will be among of those who donate π
I would like to ask you if there is posibility of getting slide which you are using in your lecture as revision to us:) for example in absract factory you explain a lot of stuff out of codes need to welled understood and revised
You’re very welcome π There is no reason to donate. Your appreciation is more then enough. I may be able to get you a slide from the presentation. I didn’t keep them neat because I wasn’t planning on using them again. What slide do you specifically need?
Ur so Kind Mr Derek :)In nowdays its very rear to find the people like you :)May God Blessing You..Amin,okaay for now i would like to have slides on factory design and abstract factory design π
I help the best that I can. I’m not sure how to get the presentation to you. The whole presentation in PDF format is 250 MB. Do you have any ideas?
What if we use DropBox π
Here is the link to everything on dropbox in PDF form https://dl.dropboxusercontent.com/u/10149293/Design%20Patterns%20PDF.pdf
Sorry about the mess
Thanks very much Mr Derek :)Am the one who suppose to say sorry for ur time π
Always feel free to ask questions. I’m very happy to help.
Thanks a lot Derek. I have been trying to learn design patterns since a long time using other resources on the internet, but every time I started, I lost interest in the middle (rather the material I was following made it so).
But your videos are excellent, easy to follow are very crisp.
Thanks a lot.
-Manju
You’re very welcome Manju π I’m happy that I was able to help with design patterns.
Hey Derek very nice tutorial! I just don’t see how to expand this with various types of EnemyShip, can you make an example of how it would be?
Thanks.
Thank you π I cover the Abstract factory again here. I hope it helps.
I have been studying and following you and the videos since a long time. I really loved them all, You are a rockstar!
Thank you very much π I’m very happy that you enjoy them.
Hi Derek! Thank you for the tutorial you made and it is simply awesome! What you did is so meaningful to guide people who really want to learn how to code correctly.
Actually I have a question here, so how do you decide whether to use an abstract class or an interface when you want to abstract things out? I noticed that you used an interface when you have all the methods to be abstract, and used an abstract class when you have something to share with its subclasses.
But I heard people say that you should use an abstract class when you want to specify that the class is a type of its super class. Just like UFOBossEnemyShip extends EnemyShip and UFOBossEnemyShips are one kind of EnemyShips. But what about ESWeapon? I know it is fully abstract and you used an interface to represent it. But can I set it as an abstract class as well just because ESUFOGun is one type of ESWeapon?
Thank you in advance!
You’re very welcome π I’m very happy that you found the video useful. All programmers have opinions on how to do certain things and this is just my opinion. If I can keep all methods abstract in my opinion it should always be an interface. If not following that rule in some way improves your ability to understand the code though feel free to not follow it. I hope that helps.
Got it. Thank you for the explanation! π
Derek could you please explain how the strategy design pattern is used in the engine and weapon sub classes?
Thanking you.
Here is another tutorial on the Abstract Factory Design Pattern. Maybe it will help explain it better.
Thanks a lot Mr Derek . But to my mind , this tutorial seems to be too complicated .
Your welcome π I cover abstract factories again in my refactoring tutorials. Maybe they will help.
hi derek!,
After watching and trying to analyse this tutorial in great detail this is what I came to conclusion :
abstract factory compels one to select the class (for creation of object ) according to user input, then implement the code(abstract method ) strictly according to guidelines provided by interfaces at each stage.
Is this right ?
Yes you got it π
yay,
thanks for your tutorial!!
You’re very welcome π