7.9. Observing Additions and Modifications to a Hashtable

Problem

You have multiple objects that need to observe modifications to a Hashtable. When an item is added, deleted, or modified in the Hashtable, each of these observer objects should be able to vote to allow or disallow the action. In order for an action to be allowed to complete, all observer objects must vote to allow the action. If even one observer object votes to disallow the action, the action is prevented.

Solution

Use the HashtableObserver class to observe additions and modifications to a HashtableSubject object that is registered with this object. The HashtableSubject class is an extension of the regular Hashtable class and allows itself to be observed by the HashtableObserver class. Its source code is:

public class HashtableSubject : Hashtable { public event HashtableEventHandler BeforeAddItem; public event HashtableEventHandler AfterAddItem; public event HashtableEventHandler BeforeChangeItem; public event HashtableEventHandler AfterChangeItem; protected virtual bool OnBeforeAdd(HashtableEventArgs e) { if (BeforeAddItem != null) { BeforeAddItem(this, e); return (e.KeepChanges); } return (true); } protected virtual void OnAfterAdd(HashtableEventArgs e) { if (AfterAddItem != null) { AfterAddItem(this, e); } } protected virtual bool OnBeforeChange(HashtableEventArgs e) { if (BeforeChangeItem != null) { BeforeChangeItem(this, e); return (e.KeepChanges); } return (true); } protected virtual void OnAfterChange(HashtableEventArgs ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.