Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Design pattern and keyword 'new'

I'm a beginning programmer. I know the basics in OOP, but I don't know the "best practices" just yet. For instance, one paradigm that continues to come up in programming is the "Abstract Factory" design pattern, which seems fairly straightforward. One of the key intents behind it is to avoid the keyword "new", because it's considered harmful. I never heard this in the courses I took in programming. Could someone elaborate on that point? Why do we want to avoid instantiating objects in this form?

like image 804
Sal Avatar asked Dec 31 '11 21:12

Sal


1 Answers

Consider in your client / caller class you write:

Vehicle v = new Car("BMW");

If your code is like the one above, you will always get a Car. In the future if you actually want a Plane, you will have to update the client code.

Alternatively, you use a factory pattern, you code something like:

Vehicle v = Factory.getVehicle();

Now you can keep the logic of getting the vehicle away (loose coupling) from the client and your client would never need a change in case you have to update the end vehicle you get. Only the Factory implementation will update and your clients will work as is.

like image 84
Nrj Avatar answered Nov 15 '22 07:11

Nrj