dimanche 26 avril 2015

Up to what extent can you prevent modifying existing code when using design patterns?

I am taking a design patterns class in school, and have read through some chapters of Head First Design Patterns. What I'd like to find out is up to what extent can design patterns prevent rewriting of existing code.

Let us take Duck classes and FlyBehavior classes for example. I have in public static void main(String[] args) the following code:

Duck mallard = new MallardDuck(new FlyWithWings());

Am I right in saying that it is inevitable that you'll have to modify your main() method when you want to add a new strategy? In that way, you are modifying existing code, right? I am specifically referring to the part where a concrete strategy class is mentioned: new FlyWithWings().

If you implemented a factory method pattern, you could have the following code:

public FlyBehavior returnBehavior(FlyBehaviorFactory factory, String behaviorType) {
    return factory.getFlyBehavior(behaviorType);
}

And then:

Duck mallard = new MallardDuck(returnBehavior(flyFactory, "wings"));

This way, a certain portion of your program does not have to know about what FlyBehaviorFactory to use. Yet, your main() method will still have to specify certain parameters in the returnBehavior method in order to know what factory will create what strategy. Thus, am I right in saying that you'll still have to modify main() if I added a new FlyBehavior class, and wanted to add that as a parameter to returnBehavior()?

Can one improve this situation any further?

Aucun commentaire:

Enregistrer un commentaire