Thursday, February 25, 2010

Design Patterns in

Observer Pattern in C#

The Observer Pattern is an often used design pattern in software development. The idea is one class (the publisher ) publishes an event (say a button click) and other objects can subscribe to that event and do something fancy when they hear about it.

The .NET framework uses delegates and events to follow the Observer pattern.

The example below allows a usercontrol (the publisher) embedded in an aspx page to tell the subscriber, in this case the aspx page when a button has been clicked.

So I can subscribe to the event BubbleClick and tell it that a new event will need to be notified when that event occurs, in this case it is a event called eventRejectRedemptionSubmit_Click in the aspx page.


public event EventHandler BubbleClick;
protected void AnEventSuchAsButtonClick(object sender, eventArgs e)
if (BubbleClick != null)
BubbleClick(this, e);


protected override void OnInit(EventArgs e)
PromotionRejectionReason1.BubbleClick += new EventHandler(eventRejectRedemptionSubmit_Click);

protected void eventRejectRedemptionSubmit_Click(object sender, EventArgs e)
PromotionApproveReceipts1.DisplayButtonsPlaceHolder = false;

The benefit of the Observer Pattern is if you want to add more subscribers to the BubbleClick event we can do so with out touching the code in the acsx control (the publisher)

No comments:

Post a Comment