Repeated properties design pattern
- by Mark
I have a DownloadManager class that manages multiple DownloadItem objects. Each DownloadItem has events like ProgressChanged and DownloadCompleted. Usually you want to use the same event handler for all download items, so it's a bit annoying to have to set the event handlers over and over again for each DownloadItem.
Thus, I need to decide which pattern to use:
Use one DownloadItem as a template and clone it as necessary
var dm = DownloadManager();
var di = DownloadItem();
di.ProgressChanged += new DownloadProgressChangedEventHandler(di_ProgressChanged);
di.DownloadCompleted += new DownloadProgressChangedEventHandler(di_DownloadCompleted);
DownloadItem newDi;
newDi = di.Clone();
newDi.Uri = "http://google.com";
dm.Enqueue(newDi);
newDi = di.Clone();
newDi.Uri = "http://yahoo.com";
dm.Enqueue(newDi);
Set the event handlers on the DownloadManager instead and have it copy the events over to each DownloadItem that is enqeued.
var dm = DownloadManager();
dm.ProgressChanged += new DownloadProgressChangedEventHandler(di_ProgressChanged);
dm.DownloadCompleted += new DownloadProgressChangedEventHandler(di_DownloadCompleted);
dm.Enqueue(new DownloadItem("http://google.com"));
dm.Enqueue(new DownloadItem("http://yahoo.com"));
Or use some kind of factory
var dm = DownloadManager();
var dif = DownloadItemFactory();
dif.ProgressChanged += new DownloadProgressChangedEventHandler(di_ProgressChanged);
dif.DownloadCompleted += new DownloadProgressChangedEventHandler(di_DownloadCompleted);
dm.Enqueue(dif.Create("http://google.com"));
dm.Enqueue(dif.Create("http://yahoo.com"));
What would you recommend?