Object-oriented – Changing behaviour of abstract class without modifying subclasses

design-patternsobject-orientedPHP

I am facing a problem with changing behaviour of a library (thus cannot or don't want to change its internals because of future updates, etc.).

In this library there is an abstract class which shares few methods with all its subclasses. Now I need to change few methods in this abstract super class without changing the subclasses. I was wondering what pattern I should apply to this without rewriting the whole thing.

I use PHP, so I could use a trait to override these methods in my own sub-subclasses which I will then use in my client code. This would result in creating the sub-subclasses and adding a trait (which is a one-liner). But I need to run PHP 5.3 which doesn't support traits.

Is there a pattern that solves this problem?

EDIT 2: the point is I don't want to change the library code, I can extend the subclasses and use them in client code but I don't want to change the code in the library itself (so I can update the library easily).

EDIT: see simplified code below

abstract class SuperClass {
    protected function doMagic() { 
        ... I need to change this ...
    }

    abstract public function execute();
}

class SubClass1 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some other code ...
    }
}

class SubClass2 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some different code ...
    }
}

Best Answer

First question--why do you need to change the logic of the abstract class? You seem to indicate that you don't want any of its current subclasses to inherit the changes, so I have to assume you want to write new subclasses which will. Given that the new subclasses don't exist yet, add a little indirection first:

abstract class SuperClass {
    protected function doMagic() { 
        ... I need to change this ...
    }

    abstract public function execute();
}

abstract class ExtendedSuperClass extends SuperClass {
    protected function doMagic() { 
        ... NEW CODE ...
    }
}


class SubClass1 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some other code ...
    }
}

class SubClass2 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some different code ...
    }
}

class SubClass3 extends ExtendedSuperClass {
    protected public execute() {
        $this->doMagic();
        ... yet more different code ...
    }
}

That is, extend the abstract class with a new abstract class, and have the classes needing the new logic extend THAT.