Reputation: 2291
I am reading about Factory pattern and understand the concept and implementation of it. But the definition is confusing me. Can someone please clarify it?
Definition: The Factory pattern is to define an interface for creating objects but delegates the object creation to the subclasses.
I was confused at delegates the object creation to the subclasses. It is delegating responsibility to factory class not to sub classes correct?
Upvotes: 2
Views: 150
Reputation: 6144
Try breaking down the definition this way,
The Factory pattern is to define an interface for creating objects (...)
First you define an interface, say,
interface IObjectFactory
{
object CreateObject();
}
This interface will basically define what the factory does and what type of objects it creates. However, it still is an interface, so to consume it, you need first to implement it.
Thus,
(...) but delegates the object creation to the subclasses.
Here, I believe the problem lies in the wording for subclasses: interfaces cannot have subclasses as they are not classes, they are interfaces. Furthermore, the whole sentence seems like a redundancy since an interface must always delegate the implementation to a class.
If you take a look at the definition on Wikipedia for Factory pattern, you'll notice that it seems similar, yet conveys the actual meaning:
The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."
Upvotes: 0
Reputation: 3649
Read: The Factory pattern is to define an interface for creating objects but delegates the object creation to the subclasses of the factory class
Notice: subclasses of the factory class
you start with a class: CheeseCakeFactory
. you have an instance of it like:
CheeseCakeFactory theFactory = new CheeseCakeFactory(); ....... (1)
then you do:
Cake aCake = theFactory.createCake(); ....... (2)
here i would agree with you that the task of creation was delegated to the factory. but now consider first line again:
CheeseCakeFactory theFactory = new SweetCakeFactory(); ....... (3)
we assume SweetCakeFactory
inherits CheeseCakeFactory
just by changing the concrete implementation of the factory, the final created product changes. Now the second line will ask the subclass to create object. this is why we say that the responsibility of instantiation is delegated to the subclasses.
Upvotes: 1
Reputation: 1505
I can't post comments yet. Or else this would be a comment.
My recommendation is to read this, Is this correct object oriented programming in php?, thoroughly. He works his way up to building a factory pattern. For context, you may be better off reading the entire thread. It's not that long and is quite enlightening.
Upvotes: 1