Thursday, February 09, 2006

Suggestion: Built in factories

Factory patterns are very useful - they allow you to switch around the object types you want to create without a user having to have any knowledge on the actual implementation.

The problem with the actual factories are that they are hard to implement and thus are usually not implemented unless you see a clear need in the future for abstraction. The rest of the time you just new up objects and use them.

What happens in the future when you realize that things are not that simple and you are going to require a factory to decide which object to create - then you must replace all of the news all over the place.

My suggestion: repurpose the new keyword to call a static method that will allow the method to choose the object to create. If that method is not implemented (or returns null?) then new will actually create the new object - else it will pass along the object created by the static method.

So for example - if I had a car object that had calls to create a car and it was called like this until now

car c = new car("Camry")


but eventually we realize that hybrids have a totally separate engine process - so we create a new called Hybrid car and we leave Car as is but we override the hybrids BuildEngine() method to create a hybrid.
Now all that has to be changed is that we add a new static method to the class
(perhaps something like this)
public static Car Car(string CarType)
if (CarType="Hybrid")
{return new HybridCar();}
return null;

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?