jeudi 16 juillet 2020

Substituting the inheritance in a decorator pattern with interfaces

I'm designing a class with multiple decorators - thereby relying on inheritance relationships. Since multiple inheritance isn't allowed in Java, I try to figure out a way to substitute all inheritance relationships [extends] with interfaces [implements].

I tried several approaches but none of them worked out. Especially my approach of multiple decorations with the same decorator is not working in my interface-conversions:

Computer computer = new Computer();

computer = new Loudspeaker(new Loudspeaker(computer));
System.out.println("My system with " + computer.buy() );

The hole approach of this pattern is designed around decorating with two loudspeakers.

This results in the printout: My system with a computer and a loudspeaker and a loudspeaker

Do you have any suggestion for getting rid of as much inheritance as possible? My hole code:

protected class Computer {

protected String buy() {
    return "a computer";
} }


public class Loudspeaker extends Decorator {

Computer computer;

public Loudspeaker(Computer c) {
    computer = c;
}

@Override
public String buy() {
    return computer.buy() + " and a loudspeaker";
}}


public abstract class Decorator extends Computer {
    protected abstract String buy();
}

Aucun commentaire:

Enregistrer un commentaire