Abstract Factory Design Pattern

Abstract Factory Design Pattern TutorialHere 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

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

Abstract Factory Design Pattern

80 Responses to “Abstract Factory Design Pattern”

  1. Greg says:

    is the whitepaper, UFO flow between the order/factory steps, available online?
    thank you,

  2. siddhartha M says:

    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.

    • admin says:

      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

  3. JJJ says:

    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.

    • admin says:

      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

  4. Khushal says:

    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!

    • admin says:

      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

  5. Arif Nadeem says:

    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

    • Derek Banas says:

      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

  6. Yongju Cho says:

    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?

    • Derek Banas says:

      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

  7. Lawrence R. Steeger says:

    The ESUFOBossEngine.java code is not highlighting on this page.

    Great tutorials!
    Thanks.

    • Derek Banas says:

      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

  8. Bill Matt says:

    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.

    • Derek Banas says:

      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

  9. Appu says:

    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.

  10. jaekwan lee says:

    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.

  11. Kalle says:

    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

    • Kalle says:

      I mean all the codes for the design pattern series.

    • Derek Banas says:

      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

      • smallg says:

        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.

  12. Balaji says:

    Excellent tutorial.. Really helped me understand the patterns better and relate to it with real life examples.. Thanks once again..

  13. a student says:

    thank you very much for your tutorials… all of them is very instructive πŸ™‚

  14. Daniela says:

    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.

  15. smallg says:

    thanks so so much Derek, for these excellent tutorials. My OOD skills have greatly improved. can’t thank you enough!!
    cheers

  16. 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 !

    • Derek Banas says:

      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.

      • Steve says:

        the electronics stuff would be amazing!
        this tutorial is amazing!

        knowledge feels so awesome! thanks a million! πŸ™‚

        • Derek Banas says:

          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

  17. Cris tan says:

    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.

    • Derek Banas says:

      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.

      • benuto says:

        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???

        • Derek Banas says:

          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.

  18. marko says:

    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?

  19. Denis says:

    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!

    • Derek Banas says:

      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.

  20. King says:

    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

  21. Manju says:

    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

  22. Felipe says:

    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.

  23. Steve Johnson says:

    I have been studying and following you and the videos since a long time. I really loved them all, You are a rockstar!

  24. Yao Hsu says:

    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!

    • Derek Banas says:

      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.

  25. Nick says:

    Derek could you please explain how the strategy design pattern is used in the engine and weapon sub classes?

    Thanking you.

  26. Chaker says:

    Thanks a lot Mr Derek . But to my mind , this tutorial seems to be too complicated .

  27. Abhishek says:

    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 ?

Leave a Reply

Your email address will not be published.

Google+