Abstract Factory Design Pattern

Last modified on October 5th, 2014 by Joe.

Factory of factories. To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need not be aware of the final concrete class that will be instantiated. You can program for the interface using the top factory.

There is also a view that abstract factory is ‘also’ implemented using prototype instead of factory methords pattern. Beginners for now please don’t yourself with that. Just go with factory methods pattern.

As there is a word ‘abstract’ in the pattern name don’t mistake and confuse it with java ‘abstract’ keyword. It is not related to that. This abstract is from object oriented programming paradim.

Sample abstract factory design pattern implementation in Java API

XML API implements abstract factory. There is a class name SchemaFactory. This acts as a factory and supports implemenation of multiple schemas using abstract factory design pattern.

Sample Java Source Code for Factory Method Design Pattern

Following is the interface, that will be returned as the final end product from the factories.

package com.javapapers.sample.designpattern.abstractfactory;

public interface Animal {
	public void breathe();
}

Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.

package com.javapapers.sample.designpattern.abstractfactory;

public interface AnimalFactory {
	public Animal createAnimal();
}

One of the factory from a predefined set which will instantiate the above interface.

package com.javapapers.sample.designpattern.abstractfactory;

public class SeaFactory implements AnimalFactory {

	public Animal createAnimal() {
		return new Shark();
	}

}

Second factory from a predefined set which will instantiate the Animal interface.

package com.javapapers.sample.designpattern.abstractfactory;

public class LandFactory implements AnimalFactory {
	public Animal createAnimal() {
		return new Elephant();
	}
}


Implementation of an Animal. This class is grouped with the first abstract factory.

package com.javapapers.sample.designpattern.abstractfactory;

public class Shark implements Animal {
	public void breathe() {
		System.out.println("I breathe in water! He he!");
	}
}

Implementation of an Animal. This class is grouped with the second abstract factory.

package com.javapapers.sample.designpattern.abstractfactory;

public class Elephant implements Animal {
	public void breathe() {
		System.out.println("I breathe with my lungs. Its easy!");
	}
}

Following class consumes the abstract factory.

package com.javapapers.sample.designpattern.abstractfactory;

public class Wonderland {
	public Wonderland(AnimalFactory factory) {
		Animal animal = factory.createAnimal();
		animal.breathe();
	}
}

Testing the abstract factory design pattern.

package com.javapapers.sample.designpattern.abstractfactory;

public class SampleAbstractFactory {

	public static void main(String args[]){
		new Wonderland(createAnimalFactory("water"));
	}

	public static AnimalFactory createAnimalFactory(String type){
		if("water".equals(type))
			return new SeaFactory();
		else
			return new LandFactory();
	}
}

Output of the above sample program for abstract factory pattern

I breathe in water! He he!

Comments on "Abstract Factory Design Pattern"

  1. Priyank says:

    hey thanks for gr8 tutorials. Can you also add singleton pattern as it is widely asked question in interviews.

  2. Joe says:

    I am working on tutorials for all GOF design patterns and will post them one by one soon.

    Will post singleton design pattern within couple of weeks.

    By the way, your website is cool Priyan!

  3. […] Abstract factory may also be used to construct a complex object, then what is the difference with builder pattern? In builder pattern emphasis is on ’step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step. But in abstract factory how complex the built object might be, it will not have step by step object construction. […]

  4. Pankaj says:

    hey thanks for gr8 tutorials it’s very useful. Can you also add Visitor pattern

  5. Ritesh says:

    G8 tutorial
    example is very easy to understand

    thanks!

  6. Sandeep says:

    Nice tutorial, nice blog, it refreshed lot of things in quite easy way.
    Thank You!

    Can you please add something on threads as well. It kills me whenever I have to work on them. I hate them alot. Maybe your way of defining things will make them lil sweet for me :)

    Thank You Again!
    Cheers

  7. […] But we declare an attribute for that same class inside and create instance for that and return it. Factory design pattern can be used to create the singleton […]

  8. Anonymous says:

    The example for Abstract Factory pattern is still missing in your blog. You have once again given the example for factory pattern.
    The example deals only with one object which is Animal here, but the Abstract Factory Pattern will handle families of objects like Animal, Tree etc..,

  9. Pundlik Oulkar says:

    Yeah,
    Your description on all java concepts is helpful for me.
    Can you please explain How one can write a immutable class?

  10. venkat says:

    can you give one more example for factorfy and abstract factory design pattern.

  11. venkat says:

    can you give diff for factory and abstract factory

  12. Raajesh says:

    Hi Joe,

    Thanks for sharing your knowledge to the world.

    Regards
    Raajesh

  13. Anonymous says:

    Thanks for sharing your knowledge to the world.

  14. Anonymous says:

    Hi Joe,
    First i would like to thank to post these articles.Can you please explain the difference between Factory method pattern and Factory pattern? From long time i am trying to understand this concept but getting more confused.

    Thanks,
    Rajani

  15. Arjun says:

    Hi Joe,

    Thanks for sharing your knowledge . your thinking and presentation is simple and dynamic.

    One request can share hibernate .

    Regards
    arjun

    Raajesh on January 27th, 2012 9:48 am

  16. Madhu says:

    HI Joe, Thanks for the article, could you please add the import statements to the programs.

  17. jp says:

    May be the most simple and straight forward article on Abstract Factory

  18. Avase says:

    Joe You are really doing a great job

  19. sami says:

    best explanation to abstract factory pattern.

  20. Harshal says:

    Hi Joe,
    Thanx for sharing the abstract factory desing pattern, it helps a lot for solving my problem…

    Regards,
    Harshal

  21. Alex says:

    thanks for sharing your knowledge.
    Great Blog. Keep it up!

  22. saniosan says:

    Great discussion,will clear any one…

  23. Indramohan G says:

    I think it resembles the example of Factory design pattern. Please correct me if i am wrong.

  24. Vinuthna says:

    Nice Article

  25. Ydder Isran says:

    Sir, Could you please provide us with that simple UML diagram for the same.

  26. […] Factory design pattern and singleton design pattern is used in implementing the flyweight. PREV POST: JDBC Introduction Add your comment: Name: Email: Website: […]

  27. santosh says:

    hey can please post UML diagram for Abstract Factory Patterns

  28. Abhishek says:

    Nice example with ultimate tutorials

  29. rajesh says:

    Very good example …give one more abstract factory method for clearly understood………

  30. Shwetanjali says:

    Very nice tutorial. I really enjoy reading your blog, it is very informative.

    Thanks

  31. Jitendra says:

    Its too good.

  32. Anonymous says:

    Joe I really like the way you explain tough topics in a simple and easy manner. Greatly appreciate your work.

  33. Anonymous says:

    Hi Joe,
    I really like your explanations and examples on design patterns and the way you make them look trivial.
    Having said that I would like to underline the fact that the above pattern is more like a Factory pattern, as in this example the AnimalFactory creates an object.Whereas Abstract Factory creates a family of related objects.
    Am I wrong or am I missing something?
    Thanks

  34. Purush says:

    What is difference between Factory Method Pattern and Abstract Factory

  35. Purush says:

    Factory Design pattern is used to create object based on Inheritence where as Abstract Factory is based on Composition of objects

  36. Sundar says:

    Your explanation is great and easy to understand . If you could also add the class diagram along with it we can understand better
    a picture is more than 1000 words :)

  37. Anuj singh says:

    hi it really very good concept how to implement factory pattern .
    thanks dude…..

  38. Danial Carter says:

    Thanx for this great study…

  39. Raj says:

    Joe, First of all many thanks for writing such a good blog. I got one doubt in Abstract Factory pattern. could you please help me on clarifying it. If the Animals that lives in Sea might have some traits that are different from the one lives in Land. So we cannot add those methods in the Animal interface. We can create a new Interface and our Shark can implement it but the problem is we cannot use the interface type as return type for the Factory Method. How do we handle these kind of scenarios

  40. komal says:

    great example

  41. ravi says:

    Nice Example

  42. mehdi ghadimi says:

    hi . tnx for design pattern articles

  43. Jay says:

    Too good, Thank you so much for your efforts to create this in such simple language to understand.

  44. Anonymous says:

    Really very useful..thank you.

  45. Gaurav says:

    1. By not providing the SETTER methods in you class. Like if you have var int i; then do not provide the

    public void setI(int i) {
    this.i = i;
    }

    by doing this u are not providing the way that can change the state.

    2. Also u can make ur class as final.

  46. Anonymous says:

    Nice tutorial!!!

  47. Thanuja says:

    I really like your writings

  48. Sunil r says:

    Thanks for writing such a good blog. I got one doubt in Abstract Factory pattern.

    How should the code handle following scenario, where multiple animals exists that live in sea and land.

    Land ex: elephant, lion, tiger
    Sea ex: shark, whale, eel

  49. Anonymous says:

    thanks

  50. pritika says:

    Very helpful tutorials..

  51. Reeba says:

    Please update the block diagram for abstract factory pattern.

  52. Anonymous says:

    miss you

  53. Anonymous says:

    Thanks Joe…it’s a great help

  54. Saurabh says:

    do abstract factory class need to declared as abstract ?
    As:
    public abstract class AbstractFactory {

    }
    Kindly provide clearification

  55. Senthil says:

    Hi Joe,

    I learned what is AF Pattern and also program to Interface not to implementation now from the above example. so I wish you to keep writing such technical blog as simple as you do.

    thanks,
    senthil

  56. Anonymous says:

    Hi,

    Thanks for the work !!
    one small rquest….
    actually in interviews I fell it wont be good enough to give examples in animal, fruit etc..
    So please provide some technical or real time examples, so that we can impress the interviewer.

    Thanks,
    Yours..

  57. Anonymous says:

    Please also provide explanation about “How Abstract factory can be implemented using Prototype”

  58. abinaya says:

    cool !!!!!thank you so much…u helped a lot in need

  59. ilayarajakumaran a says:

    IF you have one hierarchy, you have one factory. If you have two hierarchy, you should have two factories.

    What if you have multiple hierarchy, will have multiple factories. He…He…

  60. Mohd Kose Avase says:

    Hi Joe,

    Your articles are very simple and straight forward. Thanks a lot for your work

  61. Piyush Khetan says:

    Hi Joe,

    Your Post are very helpful to us.

    Thanks a lot!!

  62. pavan says:

    This is just a factory method pattern where we have introduced one level of abstraction between factories. I do not see a factory handling factories.

  63. Anonymous says:

    yes i don’t see factory of factories

  64. Hiten says:

    thanks Joe!

  65. chanaiah.k says:

    How to avoid multiple if else conditions..in abstract factory method

  66. chanaiah.k says:

    Example:
    public class SampleAbstractFactory {

    public static void main(String args[]){
    new Wonderland(createAnimalFactory(“water”));
    }

    public static AnimalFactory createAnimalFactory(String type){
    if(“water”.equals(type))
    return new SeaFactory();
    else if(“water1”.equals(type))
    return new LandFactory1();
    else if(“water2”.equals(type))
    return new LandFactory2();
    else if(“water3”.equals(type))
    return new LandFactory3();
    else if(“water4”.equals(type))
    return new LandFactory4();
    else if(“water5”.equals(type))
    return new LandFactory5();
    else if(“water6”.equals(type))
    return new LandFactory()6;
    }
    }

Comments are closed for "Abstract Factory Design Pattern".