mardi 30 juillet 2019

Change behavior without modifying base class

I have a class, let's call it A with a method foo(/*with some params*/) . I'm already using that class in my code. Now in case some param bar, that I pass to the above method, has a specific value I'd like my foo() method to return a slightly different result.

Obviously I could create a class B and copy the foo method's code, alter it a bit to fit my needs and at runtime check the value of bar and decide which class to call.

Is it possible using some design pattern to make that change with the following requirements in mind: a) keep using A in my code (probable use an InterfaceA and use that instead of A) so I won't have to change it and b) don't modify the code of class A cause it's possible to later have a class C with an altered foo() and the another and then another...

Aucun commentaire:

Enregistrer un commentaire