Design Patterns: Factory vs Factory method vs Abstract Factory
Solution 1
All three Factory types do the same thing: They are a "smart constructor".
Let's say you want to be able to create two kinds of Fruit: Apple and Orange.
Factory
Factory is "fixed", in that you have just one implementation with no subclassing. In this case, you will have a class like this:class FruitFactory {
public Apple makeApple() {
// Code for creating an Apple here.
}
public Orange makeOrange() {
// Code for creating an orange here.
}
}
Use case: Constructing an Apple or an Orange is a bit too complex to handle in the constructor for either.
Factory Method
Factory method is generally used when you have some generic processing in a class, but want to vary which kind of fruit you actually use. So:abstract class FruitPicker {
protected abstract Fruit makeFruit();
public void pickFruit() {
private final Fruit f = makeFruit(); // The fruit we will work on..
<bla bla bla>
}
}
...then you can reuse the common functionality in FruitPicker.pickFruit()
by implementing a factory method in subclasses:
class OrangePicker extends FruitPicker {
@Override
protected Fruit makeFruit() {
return new Orange();
}
}
Abstract Factory
Abstract factory is normally used for things like dependency injection/strategy, when you want to be able to create a whole family of objects that need to be of "the same kind", and have some common base classes. Here's a vaguely fruit-related example. The use case here is that we want to make sure that we don't accidentally use an OrangePicker on an Apple. As long as we get our Fruit and Picker from the same factory, they will match.interface PlantFactory {
Plant makePlant();
Picker makePicker();
}
public class AppleFactory implements PlantFactory {
Plant makePlant() {
return new Apple();
}
Picker makePicker() {
return new ApplePicker();
}
}
public class OrangeFactory implements PlantFactory {
Plant makePlant() {
return new Orange();
}
Picker makePicker() {
return new OrangePicker();
}
}
Solution 2
- How are these three patterns different from each other?
Factory: Creates objects without exposing the instantiation logic to the client.
Factory Method: Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses
Abstract Factory: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
AbstractFactory pattern uses composition to delegate responsibility of creating object to another class while Factory method design pattern uses inheritance and relies on derived class or sub class to create object
- When to use which?
Factory: Client just need a class and does not care about which concrete implementation it is getting.
Factory Method: Client doesn't know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job.
AbstactFactory: When your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details.
Abstract Factory classes are often implemented with Factory Method. Factory Methods are usually called within Template Methods.
- And also if possible, any java examples related to these patterns?
Factory and FactoryMethod
Intent:
Define an interface for creating an object, but let sub classes decide which class to instantiate. Factory Method lets a class defer instantiation to sub classes.
Product: It defines an interface of the objects the Factory method creates.
ConcreteProduct: Implements Product interface
Creator: Declares the Factory method
ConcreateCreator: Implements the Factory method to return an instance of a ConcreteProduct
Problem statement: Create a Factory of Games by using Factory Methods, which defines the game interface.
Code snippet:
Factory Pattern. When to use factory methods?
Comparison with other creational patterns:
Design start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed
Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype
References for further reading: Sourcemaking design-patterns
Solution 3
Factory - Separate Factory class to create complex object.
Ex: FruitFactory class to create object of Fruit
class FruitFactory{
public static Fruit getFruit(){...}
}
Factory Method - Instead of whole separate class for factory, just add one method in that class itself as a factory.
Ex:
Calendar.getInstance() (Java's Calendar)
Abstract Factory Method - Factory of Factory
Ex: Lets say we want to build factory for computer parts. So there are several types of computers like Laptop, Desktop, Server.
So for each compter type we need factory. So we create one highlevel factory of factories like below
ComputerTypeAbstractFactory.getComputerPartFactory(String computerType) ---> This will return PartFactory which can be one of these ServerPartFactory, LaptopPartFactory, DesktopPartFactory.
Now these 3 itself are again factories. (You will be dealing with PartFactory itself, but under the hood, there will be separate implementation based on what you provided in abstract factory)
Interface-> PartFactory. getComputerPart(String s),
Implementations -> ServerPartFactory, LaptopPartFactory, DesktopPartFactory.
Usage:
new ComputerTypeAbstractFactory().getFactory(“Laptop”).getComputerPart(“RAM”)
EDIT: edited to provide exact interfaces for Abstract Factory as per the objections in comments.
Solution 4
Based this images from Design Patterns in C#, 2nd Edition by Vaskaran Sarcar book:
1. Simple Factory Pattern
Creates objects without exposing the instantiation logic to the client.
SimpleFactory simpleFactory = new SimpleFactory();
IAnimal dog = simpleFactory.CreateDog(); // Create dog
IAnimal tiger = simpleFactory.CreateTiger(); // Create tiger
2. Factory Method Pattern
Defines an interface for creating objects, but let subclasses to decide which class to instantiate.
AnimalFactory dogFactory = new DogFactory();
IAnimal dog = dogFactory.CreateAnimal(); // Create dog
AnimalFactory tigerFactory = new TigerFactory();
IAnimal tiger = tigerFactory.CreateAnimal(); // Create tiger
3. Abstract Factory pattern (factory of factories)
Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes
IAnimalFactory petAnimalFactory = FactoryProvider.GetAnimalFactory("pet");
IDog dog = petAnimalFactory.GetDog(); // Create pet dog
ITiger tiger = petAnimalFactory.GetTiger(); // Create pet tiger
IAnimalFactory wildAnimalFactory = FactoryProvider.GetAnimalFactory("wild");
IDog dog = wildAnimalFactory .GetDog(); // Create wild dog
ITiger tiger = wildAnimalFactory .GetTiger(); // Create wild tiger
Solution 5
Every design pattern strives to help ensure that written, working code is not touched. We all know that once we touch working code, there are defects in existing working flows, and a lot more testing needs to get done to ensure that we did not break anything.
A factory pattern creates objects based on input criteria, thus ensuring that you dont need to write code like:
if (this) {
create this kind of object
} else {
that kind of object
}
A good example of this is a travel website. A travel website can only provide travel (flight, train, bus) or / and provide hotels or / and provide tourist attraction packages. Now, when a user selects next, the website needs to decide what objects it needs to create. Should it only create the travel or hotel object too.
Now, if you envision adding another website to your portfolio, and you believe that the same core be used, for example, a carpooling website, which now searches for cab's and makes payments online, you can use a abstract factory at your core. This way you can just snap in one more factory of cabs and carpools.
Both factories have nothing to do with each other, so it's a good design to keep them in different factories.
Hope this is clear now. Study the website again keeping this example in mind, hopefully it will help. And I really hope I have represented the patterns correctly :).
Related videos on Youtube
Just_another_developer
Enthusiastic Java developer, Always keen to learn new things.
Updated on July 08, 2022Comments
-
Just_another_developer almost 2 years
I was reading design patterns from a website
There I read about Factory, Factory method and Abstract factory but they are so confusing, am not clear on the definition. According to definitions
Factory - Creates objects without exposing the instantiation logic to the client and Refers to the newly created object through a common interface. Is a simplified version of Factory Method
Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.
Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes.
I also looked the other stackoverflow threads regarding Abstract Factory vs Factory Method but the UML diagrams drawn there make my understanding even worse.
Can anyone please tell me
- How are these three patterns different from each other?
- When to use which?
- And also if possible, any java examples related to these patterns?
-
Nick Alexeev over 8 yearsWhile I was looking for answers to roughly the same question as the O.P., I found this article: From No Factory to Factory Method. It provides the insight by following the evolution of a sample project (factory method mentioned in the title is one of the evolutionary steps).
-
Sheena almost 3 yearsI stumbled over this after reading the following article, which describes the problem quite well: "Codeproject- Factory methode vs. abstract factory.
-
xtofl over 11 yearsThe idea behind the
ComputerFactory
would be that you have a common creation interface (getScreen(); getKeyboard(); getDiskdrive(); ...
), not an interface per computer type as you suggest. You can smell a design issue if you use the same word twice in the same statement: LaptopFactory.getLaptopPart(). -
Ravi K over 11 yearsNo no no, don't go exactly on code itself. It was just an anology for understanding. If you want exact example with interfaces, here it is. Objects: Interface -> ComputerPart, Implementation -> RAM, HDD, Processor Factory: Interface-> PartFactory. getComputerPart(String s), Implementations -> ServerPartFactory, LaptopPartFactory, DesktopPartFactory. Abstract Factory: ComputerType.getPartFactory(“String s”) Usage: new ComputerType().getFactory(“Laptop”).getComputerPart(“RAM”)
-
Ravi K over 11 yearsI have updated answer to take care of your concern. Actually abstract factory is nothing but factoy of factory only. I gave earlier example just for reference (Assuming readers will take care of interfaces while actual implementation). Still thanks for notifying. Its always good to improve. :)
-
croraf over 10 years+1 This is the answer that is most alike to my understanding of these patterns. Adding examples of calling code (Client) would also help? Question that bothers me a lot is: can we say that Abstract Factory Pattern is just Factory extended with Factory Method Pattern (if this is true, I'm clear on this topic)?
-
Julien__ over 7 yearsNo
abstract Factory
is not a factory of factory... It's anabstract class
or aninterface
able to create object that will be implemented/extended with different concrete factories. See the accepted answer for code details. And please remove or edit your answer accordingly. -
Taztingo over 7 yearsThis is the example I've spent years looking for.
-
Tony Lin about 7 yearsFor Factory Method, shouldn't it be define a superclass?
-
Arnab Dutta about 4 years@AndréAndrade How to invoke the Factory Method ? A small code samle pls :) That will clear my doubt on its usage
-
wlnirvana about 4 yearsI like the explanation of factory method, which is concise enough to unveil why it is so named. In this pattern, the factory is the method, NOT the class who is generally not a helper utility grouping instantiation methods but meaningful on its own. Other more elaborate answers unfortunately missed this point.
-
Sangeeth Nandakumar over 2 years100% clarity. Underrated answer