Sunday, 8 November 2009

Design Patterns: Factory Method Pattern

As we all well know tight-coupling or strong dependency between classes limits developer in accomodating new changes. Further extending, adding new functionality without modifying the existing code is almost impossible. Let's have a look at the simple example:

class Producer
{
public static function createConcert(genre:String):Performer
{
if(genre == "pop"){
return new BritneySpears();
}
else if(genre == "classic"){
return new Mozart();
}
}
}

There's nothing wrong with this example. It works correctly. But what if I need to add one more genre there, say "rock"? I need to add one more "if "statement and create new type of performer - rock star (or band). So, I need to alter the code, modify it to add a new type.
This considered to be a bad practice since others might use this chunk of code and you could break it while modifying it.

No comments:

Post a Comment