I'm trying to apply the Decorator Design Pattern to the following situation:
I've 3 different kind of forms: Green, Yellow, Red.
Now, each of those forms can have different set of attributes. They can have a minimize box disabled, a maximized box disabled and they can be always on top.
I tried to model this the following way:
Form <---------------------------------------FormDecorator
/\ /\
|---------|-----------| |----------------------|-----------------|
GreenForm YellowForm RedForm MinimizeButtonDisabled MaximizedButtonDisabled AlwaysOnTop
Here is my GreenForm code:
public class GreenForm : Form {
public GreenForm() {
this.BackColor = Color.GreenYellow;
}
public override sealed Color BackColor {
get { return base.BackColor; }
set { base.BackColor = value; }
}
}
FormDecorator:
public abstract class FormDecorator : Form {
private Form _decoratorForm;
protected FormDecorator(Form decoratorForm) {
this._decoratorForm = decoratorForm;
}
}
and finally NoMaximizeDecorator:
public class NoMaximizeDecorator : FormDecorator
{
public NoMaximizeDecorator(Form decoratorForm) : base(decoratorForm) {
this.MaximizeBox = false;
}
}
So here is the running code:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(CreateForm());
}
static Form CreateForm() {
Form form = new GreenForm();
form = new NoMaximizeDecorator(form);
form = new NoMinimizeDecorator(form);
return form;
}
The problem is that I get a form that isn't green and that still allows me to maximize it. It is only taking in consideration the NoMinimizeDecorator form. I do comprehend why this happens but I'm having trouble understanding how to make this work with this Pattern.
I know probably there are better ways of achieving what I want. I made this example as an attempt to apply the Decorator Pattern to something. Maybe this wasn't the best pattern I could have used(if one, at all) to this kind of scenario. Is there any other pattern more suitable than the Decorator to accomplish this? Am I doing something wrong when trying to implement the Decorator Pattern?
The problem here is that you're not actually implementing the decorator pattern. For a proper implementation of the pattern, you need to subclass Form to create your decorator, and then intercept all operations taken on your decorator and forward them to your private Form instance. You sort of do that, except that aside from assigning a reference in the FormDecorator constructor, you never again use that private Form instance. The net result is that you create a GreenForm, then wrap it in a NoMaximizeDecorator, and then you wrap that in a NoMinimizeDecorator. But because you never forward operations taken against the NoMinimizeDecorator to the wrapped Form instance, only the NoMinimizeDecorator instance actually applies any behavior to the instance that's used. This fits with what you observe when you run your code: a standard window with a disabled Minimize button.
Form is a really bad example for creating decorators in C#, because most of its properties and methods are non-virtual, meaning if you're accessing the decorated form via a Form reference, you have no way to intercept the base class's properties - you can't effectively "wrap" Form.
EDIT
It occurs to me that the statement "Form is a really bad example for creating decorators in C#" really begs the question of what is a good example. Typically, you'll use the decorator pattern to provide a custom interface implementation without implementing the entire implementation from scratch. A very common example is generic collections. Most everything that wants list functionality doesn't depend on, e.g., List<String>, but rather on IList<String>. So, if you for example want a custom collection that won't accept strings shorter than 5 characters, you would use something like the following:
public class MinLengthList : IList<String>
{
private IList<string> _list;
private int _minLength;
public MinLengthList(int min_length, IList<String> inner_list)
{
_list = inner_list;
_minLength = min_length;
}
protected virtual void ValidateLength(String item)
{
if (item.Length < _minLength)
throw new ArgumentException("Item is too short");
}
#region IList<string> Members
public int IndexOf(string item)
{
return _list.IndexOf(item);
}
public void Insert(int index, string item)
{
ValidateLength(item);
_list.Insert(index, item);
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
public string this[int index]
{
get
{
return _list[index];
}
set
{
ValidateLength(value);
_list[index] = value;
}
}
#endregion
#region ICollection<string> Members
public void Add(string item)
{
ValidateLength(item);
_list.Add(item);
}
public void Clear()
{
_list.Clear();
}
public bool Contains(string item)
{
return _list.Contains(item);
}
public void CopyTo(string[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _list.Count; }
}
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
public bool Remove(string item)
{
return _list.Remove(item);
}
#endregion
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
return _list.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)_list).GetEnumerator();
}
#endregion
}
public class Program
{
static void Main()
{
IList<String> custom_list = new MinLengthList(5, new List<String>());
custom_list.Add("hi");
}
}
This is a misapplication of the decorator pattern. The decorator pattern is concerned with the behavior of objects. You're constructing objects which falls under the creational umbrella. While you might be able to wrap your head around "not having a maximize button" being a behavior it sounds a little off kilter.
I don't think there's a real way to fix your design though. The decorator pattern just doesn't fit. Any attempt to fix this up is just going to be incredibly crufty when you could just use a Builder.
What I could see doing is decorating the Builder of a form to perform these actions while building. It would look something like this...
public interface IFormBuilder {
public Form BuildForm();
}
public class FormBuilder : IFormBuilder {
public Form BuildForm(){
return new Form();
}
}
public class NoMaximizeFormBuilder : IFormBuilder {
private IFormBuilder _builder;
public NoMaximizeFormBuilder (IFormBuilder builder){
_builder = builder;
}
public Form BuildForm(){
f = _builder.BuildForm();
f.MaximizeBox = false;
return f;
}
}
And you could use it like this...
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(CreateForm());
}
static Form CreateForm() {
var b = new FormBuilder();
var b = new NoMaximizeFormBuilder(b);
return b.Build();
}
But even that is a little ugly. You might be able to transform this into a fluent interface for building forms.
try to make your pattern to apply the decorator properties to the same object, not creating new Forms:
public abstract class FormDecorator {
protected Form _decoratorForm;
protected FormDecorator(Form decoratorForm) {
this._decoratorForm = decoratorForm;
}
public abstract void Decorate();
}
public class NoMaximizeDecorator : FormDecorator
{
public NoMaximizeDecorator(Form decoratorForm) : base(decoratorForm) {
Decorate();
}
public override void Decorate() {
_decoratorForm.MaximizeBox = false;
}
}
And in your Main:
static Form CreateForm() {
Form form = new GreenForm();
new NoMaximizeDecorator(form);
new NoMinimizeDecorator(form);
return form;
}
Related
I need to make alternative to List<> class where I will have 4 methods... Two for adding int items, one from front, other from behind and two for deleting, one from front and other from behind as well. My class should not inherit anything.
Something like this...
public class MyList
{
public void AddItemsFront(int pItem)
{
}
public void AddItemsBehind(int pItem)
{
}
public void DeleteItemsFront(int pItem)
{
}
public void DeleteItemsBehind(int pItem)
{
}
}
You could hold an instance of a List<T> in a field, List<T> has already these methods:
public class MyList<T>
{
private List<T> _TheList;
public MyList()
{
_TheList = new List<T>();
}
public List<T> TheList { get { return _TheList; } set { _TheList = value; } }
public void AddItemFront(T pItem)
{
TheList.Insert(0, pItem);
}
public void AddItemBehind(T pItem)
{
TheList.Add(pItem);
}
public void DeleteItemFront()
{
TheList.RemoveAt(0);
}
public void DeleteItemBehind()
{
TheList.RemoveAt(TheList.Count - 1);
}
}
Since it's a generic class you could also use it for different types than int.
var myList = new MyList<int>();
myList.AddItemFront(1);
Create a class that's got a data member of the correct List<> type, and implement your methods by calling the appropriate methods on the List<> data member. You will want your delete operations to return the object they removed from the list.
This is often referred to as the Adapter pattern. Wikipedia has a page on it.
Here's some pseudo code to illustrate what I'm looking at.
public class Loader
{
public Execute()
{
var currentPage = new ItemPageDocumentBuilder();
while(reader.Read())
{
currentPage.Add(reader.XmlDoc);
}
}
private class ItemsToLoad
{
private XmlDocument _page
public void Add(XmlElement itemelement)
{
_page.DocumentElement.AppendChild(itemElement);
}
}
}
I need to derive a class from Loader, and then override the Add method of the ItemsToLoad class inside it, and then call base.Execute(). In other words I want the Execute() method of my derived class to be exactly the same as that of Loader, but to use the overridden Add method of ItemsToLoad to to its work.
I suspect the neatest way to do this would be to remove ItemsToLoad from inside Loader, and make it abstract, correct?
If I couldn't do that, out of interest, what's the best solution?
If I understand your requirement, you have two responsabilities: executing something (which is always the same), and adding something (which differs).
I would do it much simpler, without inheritance and inner classes.
For the adding task, you define an interface:
public interface IItemAdder
{
void Add();
}
And one ore more implementations:
public class ItemAdder1 : IItemAdder
{
public void Add()
{
// specific implementation here
}
}
Then, you have a Loader, in which you inject a specific instance of item adder:
public class Loader : ILoader
{
private IItemAdder _itemAdder;
public Loader(IItemAdder itemAdder)
{
_itemAdder = itemAdder;
}
public void Execute()
{
// use injected item adder to do work
_itemAdder.Add();
}
}
public interface ILoader
{
void Execute();
}
And so usage is:
var loader = new Loader(new ItemAdder1());
loader.Execute();
This way everything is injected, can be replaced and mocked easily; and you clearly separate concerns.
Here is a suggestion (Syntax might not be correct though):
public class Loader
{
ItemsToLoad item;
public Loader(ItemsToLoad item) {
this.item = item;
}
public Execute()
{
// do things using item like item.add();
}
}
interface ItemsToLoad
{
void add();
}
class ItemsToLoad1: ItemsToLoad
{
void add(){
// implementation
}
}
class ItemsToLoad2: ItemsToLoad
{
void add(){
// implementation
}
}
And here is how to use them;
ItemsToLoad item;
if (some condition) {
item = new ItemsToLoad1()
} else {
item = new ItemsToLoad2()
}
Loader loader = new Loader(item);
loader.execute();
You can inherit both classes and inject child sub-class object to its parent.
class Loader
{
public void Execute(ItemsToLoad argObj)
{
if(argObj == null)
argObj = new ItemsToLoad();
argObj.Add(19);
}
public class ItemsToLoad
{
public virtual void Add(int a)
{
Console.WriteLine("Reached ItemsToLoad.");
}
}
}
class ChildLoader:Loader
{
public void Execute(ItemsToLoad argObjLoader)
{
if (argObjLoader == null)
argObjLoader = new ChildItemsToLoad();
base.Execute(argObjLoader);
}
class ChildItemsToLoad : Loader.ItemsToLoad
{
public override void Add(int b)
{
Console.WriteLine("Reached ChildItemsToLoad.");
}
}
}
And can start with
ChildLoader obj999 = new ChildLoader();
obj999.Execute(null);
I need to derive a class from Loader, and then override the Add method of the ItemsToLoad class inside it, and then call base.Execute(). In other words I want the Execute() method of my derived class to be exactly the same as that of Loader, but to use the overridden Add method of ItemsToLoad to to its work.
You need to override Loader, not ItemsToLoad. You haven't shown the code that uses ItemsToLoad, so it's difficult to be specific - but at the very least, you would need to override the new ItemsToLoad to point to your subclass. Also, ItemsToLoad is private - meaning you can't use it except from within Loader. As it is now, you'd need a completely rewritten ItemsToLoad and to override every method in Loader that uses ItemsToLoad.
If you control the Loader class, the easiest changes would probably be to abstract out the creating of ItemsToLoad and open up ItemsToLoad so it can be subclassed. Something like:
public class Loader {
private ItemsToLoad Items { get; set; }
protected virtual ItemsToLoad CreateItemsToLoad() {
return new ItemsToLoad();
}
protected class ItemsToLoad {
public virtual void Add() {
}
}
}
public class MyOtherLoader : Loader {
protected override ItemsToLoad CreateItemsToLoad() {
return new MyOtherItemsToLoad();
}
private class MyOtherItemsToLoad : ItemsToLoad {
public override void Add() {
}
}
}
The code below throws an exception because the abstract constructor is called before the child constructor.
I need to provide an abstract class to capsule some logic from a different part of the program. However i also need to check if the abstract members are initialised correctly rigth after creation without the childclass having any influence over this.
the compiling example below should illustrate my question.
using System;
namespace Stackoverflow
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
Thing childthing;
public Child(Thing provided) : base(){
childthing = provided;
}
public override void Initialise(){
//Exception is thrown here - childthing is still null
parentthing = childthing.Add(1);
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent(){
Initialise();
AssertThingyNotNull();
}
private void AssertThingyNotNull(){
if (parentthing == null) throw new Exception("Waaa");
}
public abstract void Initialise();
}
class Thing
{
private int i;
public Thing(int i){
this.i = i;
}
public Thing Add(int b){
i += b;
return new Thing(i);
}
}
}
Edit #1:
Is there some way to do this by reflecting into the caller (should be the creator of child rigth?) and then reacting on the end of that call?
Edit #2:
Getting the .ctor that creates the child is easy. Manipulating the methods seems something between impossible and a bad idea.
foreach (StackFrame frame in new StackTrace().GetFrames())
{
Console.WriteLine(frame.GetMethod().Name);
}
You can't, basically. This is why you should avoid calling virtual (or abstract) members from a constructor as far as possible - you could end up with code which is running with an incomplete context. Any variable initializers are executed before the base class constructor is called, but none of the code within the constructor body is.
If you need to perform initialization and only want to do that when the derived class constructor is running, then just call Initialise from the derived class constructor to start with.
You can do something similar to what Microsoft did with InitializeComponent()
then let the children call it whenever it can.
Try this.
Edited = cleaner version.
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var x = new Thing(5);
var y = new Child(x);
}
}
class Child : AbstractParent
{
public Child(Thing provided)
: base()
{
parentthing = provided;
base.Initialise();
}
}
abstract class AbstractParent
{
protected Thing parentthing;
public AbstractParent()
{
}
private void AssertThingyNotNull()
{
if (parentthing == null) throw new Exception("Waaa");
}
public void Initialise()
{
AssertThingyNotNull();
}
}
class Thing
{
private int i;
public Thing(int i)
{
this.i = i;
}
public Thing Add(int b)
{
i += b;
return new Thing(i);
}
}
}
Suppose you had such code:
public Base
{
abstract void Register();
}
public Registrator1: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
public Registrator2: Base
{
override void Register()
{
//uses the current state of the object to populate the UI captions
}
}
But When you receive a new business rule asking you to write Registrator3 which actually registers based on some parameter and you change your code base to the next:
public Base
{
abstract void Register(externalParam);
}
public Registrator1: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate theUI
}
}
public Registrator2: Base
{
override void Register(externalParam)
{
//uses the current state of the object to populate the UI
}
}
public Registrator3: Base
{
override void Register(externalParam)
{
//uses a DDD - service passed in the params to populate the UI
}
}
But Registrator1 and Registrator2 do not need that param and the code becomes smelly. What are the ways to re-write this code?
You could use an object as a parameter here; which is commonly used in scenarios where the number of parameters can vary depending on the call being used.
struct RegistrationInfo
{
public static readonly RegistrationInfo Empty = new RegistrationInfo();
public string Username;
public string CustomerName;
public string Validity;
}
abstract class Base
{
public abstract void Register(RegistrationInfo info);
// If you want to retain the paramaterless call:
public void Register()
{
Register(RegistrationInfo.Empty);
}
}
class Registrar1 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.Username == null) throw new ArgumentNullException("info.Username");
}
}
class Registrar2 : Base
{
public override void Register(RegistrationInfo info)
{
if (info.CustomerName == null) throw new ArgumentNullException("info.CustomerName");
}
}
This has the advantage that you don't need to change method parameters (which is breaking interface) each time a parameter is added. The usage also becomes somewhat self-documenting:
var r = new Registrar1();
r.Register(new RegistrationInfo(){ Username = "JimJoe" });
r.Register(RegistrationInfo.Empty);
It's like air freshener for this type of code smell, while it's still smelly; you can make it smell nicer.
Finally you can make the call-site cleaner by making it a params argument (this has a small amount of overhead); in all honesty though it is more smelly because it's a language hack. Finally you could improve it with generics:
class RegistrationInfo
{
}
class RegistrationInfo1 : RegistrationInfo
{
public string Arg;
}
class RegistrationInfo2 : RegistrationInfo
{
public int Arg;
}
interface IBase<in TRegistration>
where TRegistration : RegistrationInfo
{
void Register(TRegistration registration);
}
class Base : IBase<RegistrationInfo>
{
public void Register(RegistrationInfo registration)
{
}
}
class Registrar1 : IBase<RegistrationInfo1>
{
public void Register(RegistrationInfo1 arg)
{
}
}
class Registrar2 : IBase<RegistrationInfo2>
{
public void Register(RegistrationInfo2 arg)
{
}
}
Is it not possible to contain the logic for externalParam in Registrator3?
In other words, Registrator3 uses the param, then calls the unmodified parameterless base?
A lot really depends on where the logic belongs. If it is something intrinsic to the base, then put it in the base, and either overload the Register() function or supply a default value for the param so that sub classes don't need to provide it.
Assuming you want to reuse the registration logic from the base class, you could update the code as follows:
public class Base
{
public virtual void Register(object externalParam)
{
// base registration logic goes here
}
}
public class Registrator1: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator2: Base
{
public override void Register(object externalParam)
{
base.Register(null);
// custom registration logic goes here
}
}
public class Registrator3: Base
{
public override void Register(object externalParam)
{
base.Register(externalParam);
// custom registration logic goes here
}
}
HTH,
Cosmin
EDIT: Updated code to compile.
I want to create a class that can be used to represent a dynamically computed value, and another class that represents a value can be the source (subject) for these dynamically computed values. The goal is that when the subject changes, the computed value is updated automatically.
It seems to me that using IObservable/IObserver is the way to go. Unfortunately I can't use the Reactive Extensions library, so I am forced to implement the subject/observer pattern from scratch.
Enough blabla, here are my classes:
public class Notifier<T> : IObservable<T>
{
public Notifier();
public IDisposable Subscribe(IObserver<T> observer);
public void Subscribe(Action<T> action);
public void Notify(T subject);
public void EndTransmission();
}
public class Observer<T> : IObserver<T>, IDisposable
{
public Observer(Action<T> action);
public void Subscribe(Notifier<T> tracker);
public void Unsubscribe();
public void OnCompleted();
public void OnError(Exception error);
public void OnNext(T value);
public void Dispose();
}
public class ObservableValue<T> : Notifier<T>
{
public T Get();
public void Set(T x);
}
public class ComputedValue<T>
{
public T Get();
public void Set(T x);
}
My implementation is lifted mostly from: http://msdn.microsoft.com/en-us/library/dd990377.aspx.
So what would the "right" way to do this be? Note: I don't care about LINQ or multi-threading or even performance. I just want it to be simple and easy to understand.
If I were you I would try to implement your classes as closely as possible to the way Rx has been implemented.
One of the key underlying principles is the use of relatively few concrete classes that are combined using a large number of operations. So you should create a few basic building blocks and use composition to bring them all together.
There are two classes I would take an initial look at under Reflector.NET: AnonymousObservable<T> & AnonymousObserver<T>. In particular AnonymousObservable<T> is used through-out Rx as the basis for instantiating observables. In fact, if you look at the objects that derive from IObservable<T> there are a few specialized implementations, but only AnonymousObservable<T> is for general purpose use.
The static method Observable.Create<T>() is essentially a wrapper to AnonymousObservable<T>.
The other Rx class that is clearly a fit for your requirements is BehaviorSubject<T>. Subjects are both observables and observers and BehaviorSubject fits your situation because it remembers the last value that is received.
Given these basic classes then you almost have all of the bits you need to create your specific objects. Your objects shouldn't inherit from the above code, but instead use composition to bring together the behaviour that you need.
Now, I would suggest some changes to your class designs to make them more compatible with Rx and thus more composible and robust.
I would drop your Notifier<T> class in favour of using BehaviourSubject<T>.
I would drop your Observer<T> class in favour of using AnonymousObserver<T>.
Then I would modify ObservableValue<T> to look like this:
public class ObservableValue<T> : IObservable<T>, IDisposable
{
public ObservableValue(T initial) { ... }
public T Value { get; set; }
public IDisposable Subscribe(IObserver<T> observer);
public void Dispose();
}
The implementation of ObservableValue<T> would wrap BehaviourSubject<T> rather than inherit from it as exposing the IObserver<T> members would allow access to OnCompleted & OnError which wouldn't make too much sense since this class represents a value and not a computation. Subscriptions would use AnonymousObservable<T> and Dispose would clean up the wrapped BehaviourSubject<T>.
Then I would modify ComputedValue<T> to look like this:
public class ComputedValue<T> : IObservable<T>, IDisposable
{
public ComputedValue(IObservable<T> source) { ... }
public T Value { get; }
public IDisposable Subscribe(IObserver<T> observer);
public void Dispose();
}
The ComputedValue<T> class would wrap AnonymousObservable<T> for all subscribers and and use source to grab a local copy of the values for the Value property. The Dispose method would be used to unsubscribe from the source observable.
These last two classes are the only real specific implementation your design appears to need - and that's only because of the Value property.
Next you need a static ObservableValues class for your extension methods:
public static class ObservableValues
{
public static ObservableValue<T> Create<T>(T initial)
{ ... }
public static ComputedValue<V> Compute<T, U, V>(
this IObservable<T> left,
IObservable<U> right,
Func<T, U, V> computation)
{ ... }
}
The Compute method would use an AnonymousObservable<V> to perform the computation and produce an IObservable<V> to pass to the constructor of ComputedValue<V> that is returned by the method.
With all this in place you can now write this code:
var ov1 = ObservableValues.Create(1);
var ov2 = ObservableValues.Create(2);
var ov3 = ObservableValues.Create(3);
var cv1 = ov1.Compute(ov2, (x, y) => x + y);
var cv2 = ov3.Compute(cv1, (x, y) => x * y);
//cv2.Value == 9
ov1.Value = 2;
ov2.Value = 3;
ov3.Value = 4;
//cv2.Value == 20
Please let me know if this is helpful and/or if there is anything that I can elaborate on.
EDIT: Also need some disposables.
You'll also need to implement AnonymousDisposable & CompositeDisposable to manage your subscriptions particularly in the Compute extension method. Take a look at the Rx implementations using Reflector.NET or use my versions below.
public sealed class AnonymousDisposable : IDisposable
{
private readonly Action _action;
private int _disposed;
public AnonymousDisposable(Action action)
{
_action = action;
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
_action();
}
}
}
public sealed class CompositeDisposable : IEnumerable<IDisposable>, IDisposable
{
private readonly List<IDisposable> _disposables;
private bool _disposed;
public CompositeDisposable()
: this(new IDisposable[] { })
{ }
public CompositeDisposable(IEnumerable<IDisposable> disposables)
{
if (disposables == null) { throw new ArgumentNullException("disposables"); }
this._disposables = new List<IDisposable>(disposables);
}
public CompositeDisposable(params IDisposable[] disposables)
{
if (disposables == null) { throw new ArgumentNullException("disposables"); }
this._disposables = new List<IDisposable>(disposables);
}
public void Add(IDisposable disposable)
{
if (disposable == null) { throw new ArgumentNullException("disposable"); }
lock (_disposables)
{
if (_disposed)
{
disposable.Dispose();
}
else
{
_disposables.Add(disposable);
}
}
}
public IDisposable Add(Action action)
{
if (action == null) { throw new ArgumentNullException("action"); }
var disposable = new AnonymousDisposable(action);
this.Add(disposable);
return disposable;
}
public IDisposable Add<TDelegate>(Action<TDelegate> add, Action<TDelegate> remove, TDelegate handler)
{
if (add == null) { throw new ArgumentNullException("add"); }
if (remove == null) { throw new ArgumentNullException("remove"); }
if (handler == null) { throw new ArgumentNullException("handler"); }
add(handler);
return this.Add(() => remove(handler));
}
public void Clear()
{
lock (_disposables)
{
var disposables = _disposables.ToArray();
_disposables.Clear();
Array.ForEach(disposables, d => d.Dispose());
}
}
public void Dispose()
{
lock (_disposables)
{
if (!_disposed)
{
this.Clear();
}
_disposed = true;
}
}
public IEnumerator<IDisposable> GetEnumerator()
{
lock (_disposables)
{
return _disposables.ToArray().AsEnumerable().GetEnumerator();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public bool IsDisposed
{
get
{
return _disposed;
}
}
}