vendredi 20 septembre 2019

Decorator pattern that replace behaviour instead of adding

I've read a lot of posts and understand that decorator pattern is supposed to add functionality to the existing object. However, I have a scenario where one behaviour is replaced, not extended. To demonstrate, assume that I have these classes:

public interface IDoStuff {
    string DoStuff();
    string DoOtherStuff();
}

public class A : IDoStuff {
    public A(){}
    public string DoStuff() {
        ....
    }

    public string DoOtherStuff() {
        ....
    }
}


public class B : IDoStuff {
    protected readonly IDoStuff decoratee;

    public B(IDoStuff decoratee){ 
        this.decoratee = decoratee;
    }

    public string DoStuff() {
        decoratee.DoStuff();
        //More code
    }

    public string DoOtherStuff() {
        ....
        // This does not call decoratee.DoOtherStuff
    }
}

While I decorated the B.DoStuff method, but its DoOtherStuff method is a totally different implementation and cannot reuse the base object at all.

Am I implementing it correctly? Or is this an entirely different pattern?

Aucun commentaire:

Enregistrer un commentaire