I am trying to understand the factory design pattern better.
I understand that the pattern usually includes the following (is this always the case?):
1. Product
2. Concrete Product
3. Creator
4. Concrete Creator
From what I understand, the point of the factory method is that the Creator might look like
Public abstract class Creator
public void doSomething(){
Product product= createProduct();
product.doSomethingElse();
}
public abstract Product createProduct();
}
where createProduct()
is the factoryMethod.
Then when the Concrete Creator is created, we override Creator.createProduct()
.
If this factory method is only used for creating a product, does that mean we can technically not have a factory method, but still follow the Factory pattern?
For example, instead of
Public ConcreteCreator extends Creator{
public Product createProduct(){
return new ConcreteProduct()
}
}
we do something like
Public ConcreteCreator extends Creator{
Product product;
public ConcreteCreator(){
this.product = new ConcreteProduct;
}
}
and change the Creator to something like
Public abstract class Creator
Product product;
public void doSomething(){
this.product.doSomethingElse();
}
}
It seems like this is basically doing the same thing as the factory pattern, where the concreteproduct still responsible for creating its own ConcreteProducts, except it does it in the constructor instead of overriding the factory methods.
Is this only not done because it's cleaner to move the creation logic of the ConcreteProducts out of the constructor into a factory method (i.e. only create concrete products as needed etc)? Or is there some case where we wouldn't be able to maintain the same behaviour if we only created the ConcreteProducts in the constructor of the ConcreteCreator?