This example returns an object of type Mac
and it can never be anything different:
$mac = new Mac();
It can't be a subclass of Mac
, not can it be a class that matches the interface of Mac
.
Whereas the following example may return an object of type Mac
or whatever other type the factory decides is appropriate.
$appleStore = new AppleStore();
$mac = $appleStore->getProduct('mac');
You might want a set of subclasses of Mac
, each representing a different model of Mac. Then you write code in the factory to decide which of these subclasses to use. You can't do that with the new
operator.
So a factory gives you more flexibility in object creation. Flexibility often goes hand in hand with decoupling.
Re your comment: I wouldn't say never use new
. In fact, I do use new
for the majority of simple object creation. But it has nothing to do with who is writing the client code. The factory pattern is for when you want an architecture that can choose the class to instantiate dynamically.
In your Apple Store example, you would probably want some simple code to instantiate a product and add it to a shopping cart. If you use new
and you have different object types for each different product type, you'd have to write a huge case
statement so you could make a new
object of the appropriate type. Every time you add a product type, you'd have to update that case
statement. And you might have several of these case
statements in other parts of your application.
By using a factory, you would only have one place to update, that knows how to take a parameter and instantiate the right type of object. All places in your app would implicitly gain support for the new type, with no code changes needed. This is a win whether you're the sole developer or if you're on a team.
But again, you don't need a factory if you don't need to support a variety of subtypes. Just continue to use new
in simple cases.