dimanche 10 décembre 2017

Decorator Pattern, via inheritance or dependency injection?

Right now I am studying the common design patterns and for the most part I understand the purpose of the decorator pattern. But what I don't get is, what is the purpose of wrapping an existing object in a decorator class?

Consider this scenario, since Progress is part of the observer pattern, I want to limit the amount of updates to its subscribers to prevent the UI thread from locking.

So I have decorated the class to only update once every 50 milliseconds.

public class ProgressThrottle<T> : Progress<T>
{
    private DateTime _time = DateTime.Now;
    public ProgressThrottle(Action<T> handler) : base(handler)
    {
    }

    protected override void OnReport(T value)
    {
        if (DateTime.Now.AddMilliseconds(50) < _time)
        {
            base.OnReport(value);
            _time = DateTime.Now;
        }
    }
}

public class ProgressThrottle2<T> : IProgress<T>
{
    private DateTime _time = DateTime.Now;

    private readonly IProgress<T> _wrapper;

    public ProgressThrottle2(IProgress<T> wrapper)
    {
        _wrapper = wrapper;
    }

    public void Report(T value)
    {
        if (DateTime.Now.AddMilliseconds(50) < _time)
        {
             _wrapper.Report(value);
            _time = DateTime.Now;

        }
    }

Both classes accomplish the same thing, except I find the first version better because it allows me to use the base constructor for setting the delegate for progress updates. The base class already supports overriding the method, so what is the need for me wrap the object?

Are both classes example of the decorator pattern? I would much rather use the first option but I rarely see examples in that manner.

Aucun commentaire:

Enregistrer un commentaire