Now I am studying general design patterns, and for the most part I understand the purpose of the decorator pattern. But what I donβt understand, what is the purpose of wrapping an existing object in the decorator class?
Consider this scenario, since Progress is part of the observer pattern, I want to limit the number of updates for my subscribers to prevent blocking the user interface flow.
So, I decorated the class to update it only 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 do the same thing, except that I find the first version better because it allows me to use the base constructor to set the delegate to update progress. The base class already supports method overrides, so why should I wrap an object?
Are both classes an example decorator pattern? I would prefer to use the first option, but I rarely see examples this way.
source share