Fine-grained decorator pattern

I understand the Decorator pattern, it has the simplest terms. The idea is that one class wraps another, where the decorator method wants to run some other code before and / or after calling the same method on the decorated object.

However, I came across a situation where I cannot just name the decorated method, as it has some undesirable side effects. However, I do want most of this styled method to run.

So, I believe that I need to divide the decorated method into several methods, then in the decorator I can call some of them, run my decoration code, and then call some others - skipping the side effect that I don’t want.

However, to maintain polymorphism, this would mean adding these methods to the interface that decorated and decorator objects implement. This is undesirable; they should not be public, and this actually means that the decorated class knows how it will be decorated.

I believe that the template template is perhaps more appropriate where the abstract base class refers to each of the smaller methods, in turn, where the “decorator” simply provides an alternative implementation to the ones it cares about. However, this is not exactly a “composition over inheritance”, so what do you recommend?

+3
source share
2 answers

, API Command-Query Separation, API.

, , , , .

public interface IMyInterface
{
    Foo GetFoo(Bar bar);
}

public class MyClass : IMyInterface
{
    public Foo GetFoo(Bar bar)
    {
        this.DoSomethingWithSideEffects(bar);
        return this.DoSomethingToGetFoo(bar);
    }

    public Foo DoSomethingToGetFoo(Bar bar)
    {
        // ...
    }

    public void DoSomethingWithSideEffects(Bar bar)
    {
        // ...
    }
}

public class MyDecorator : IMyInterface
{
    private readonly MyClass mc;

    public MyDecorator(MyClass mc)
    {
        // put Null Guard here...
        this.mc = mc;
    }

    public Foo GetFoo(Bar bar)
    {
        return this.mc.DoSomethingToGetFoo(bar);
    }
}

, MyDecorator MyClass IMyInterface.

+1

, . , ... , , "... : , , ".

+2

Source: https://habr.com/ru/post/1728943/


All Articles