Change behavior without modifying base class

mt0s :

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...

Andrew Tobilko :

You could define B which would extend the interface that A implemented and have A (or better, the interface type) as a field.

interface AbstractA {
   void foo(Object o);
}
class A implements AbstractA {
  @Override
  public void foo(Object o) {}
}

class B implements AbstractA {
  private AbstractA abstractA;

  @Override
  public void foo(Object o) {
    abstractA.foo(o);
    // "a slightly different result"
  }
}

It's an example of the decorator pattern, which, as Wikipedia puts it,

allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129063&siteId=1