SlideShare a Scribd company logo
The .NET
Event Model
Michael Heron
Introduction
 Event driven programming is a philosophy for
building GUI applications.
 Most modern programming languages
incorporate a facility for event driven
programming.
 The mechanism by which events can be created
and handled varies from language to language.
 It tends to be markedly different in OO languages
from non OO languages.
 For the next few lectures, we are going to be
looking at .NET.
 Specifically, C#
Event Driven Programming – In
Brief
 Console applications are system driven.
 The user is just a puppet.
 The flow of execution is with the computer.
 Modern GUI based applications are user
driven.
 The computer is just a puppet.
 The flow of execution is with the user.
 This is reflected in a shift from processing
intensive to interaction intensive applications.
Process Intensive
 Interaction is usually limited to prompts for
information.
 How many of these
 For how long
 Computer does large amounts of processing
with relatively few configuration details.
 Simulations
 Complex AI routines
 Batch processing
Interaction Intensive
 User drives the application.
 Processing is usually short and focused.
 Locus of control inverted from the Olden Days.
 Focus is on user involvement in the process.
 Word processors
 Games
 Pretty much any modern GUI application
 Requires a new way of building programs.
Event Driven Programming
 In event driven programs, system driven
by user interactions.
 Click a button
 Move a scrollbar
 Type in a textbox
 All interactions with a system component
generate events.
 Events contain information regarding the
precise nature of the interaction
Event Driven Programming
 Each GUI component is responsible for
dispatching information on events to
interested parties.
 Usually functions in a program.
 Components hold an internal list of listeners.
 Things that are listening for specific kind of
events.
 Each listener, or handler, is responsible for
dealing with its response to the event
occurring.
Event Models – VB (Pre .NET)
 Listener functions indicated by naming
convention.
 Function for deal with a click event on a control
called cmdButton was called cmbButton_click.
 Somewhat limited.
 Stuck with predefined naming format.
 No way for multiple functions to indicate an
interest.
 No longer the model used for VB in the .NET
framework.
Event Models - Java
 Objects indicate their interest in an event by marking
themselves as a listener.
 Object oriented structure of the language allows for
each listener to define the handler method.
 Listeners defined by implementation of an interface
 Correct methods indicated by naming convention.
 actionPerformed for button clicks
 adjustmentValueChanged for adjustment events
 More flexible, but still somewhat clumsy.
 One single method must manage events from many
different components.
Event Models - .NET
 Components hold a list of delegates.
 Each delegate contains a pointer to a function.
 Direct mapping in .NET from event to
delegates.
 Delegates act as a wrapper around a function
call.
 Each component can have its own method.
 Each component can handle multiple
different listeners.
 This is known as multicasting.
 Best model so far?
Event Driven Programming
and OO
 The event handler methods called when a
method is fired get specifically configured
objects as a parameter.
 They hold the state information associated with
the event.
 These all stem from a common OO core
 Polymorphism in Java permits compile time
checking of event structure.
 Delegate structure permits separation of
abstraction and implementation.
Delegates – The Basics
 Works like a type safe function pointer.
 A variable that acts as an invokeable
reference to a function.
 Delegates are objects.
 Wrappers around the function pointer.
 They provide a syntactically neat
encapsulation of listener status.
 And can be polymorphically assessed to
ensure compile-time correction.
Delegates in Actionusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
public delegate int HandleArithmetic (int num1, int num2);
class Program
{
public static int addTwoNumbers(int num1, int num2)
{
return num1 + num2;
}
public static int multiplyTwoNumbers(int num1, int num2)
{
return num1 * num2;
}
static void Main(string[] args)
{
HandleArithmetic adding =new HandleArithmetic(addTwoNumbers);
HandleArithmetic multiplying = new HandleArithmetic(multiplyTwoNumbers);
Console.Out.WriteLine("Delegate one = " + adding(10, 20));
Console.Out.WriteLine("Delegate two = " + multiplying (10, 20));
Console.ReadLine();
}
}
}
Delegates – The Basics
 Delegates allow for the implementation of
a syntactically safe callback.
 Works on the Hollywood Principle
 When attached to an event, they let us
define a function stub that is called when
specific processes are started / finished
 Ideal mechanism for safely handling
event invocation.
Delegates – For Reals
 Delegates are just a mechanism used for .NET
event handling.
 That’s not all they are.
 You can think of a delegate as a
combination of an object/method reference,
and potentially a reference to another
delegate.
 Chain of command pattern.
 Will invoke the next element in a chain when
one exists.
Delegates – For Reals
 Small performance overhead associated
with delegates.
 Not as much as it used to be
 Considerable leeway given for compile-
time optimization.
 This is a consequence of the very strict rules
governing delegate construction.
Delegates
 Delegates get added directly to the
event type of the component.
 Delegates are usually an instance of the
EventHandler class
 Most of this is handled automatically for you
in Visual Studio .NET:
this.cmdButton.Click += new System.EventHandler
(this.HandleClick)
The Structure of Events in .NET
 Different terminology is used here.
 Consumer and Producer
 Dispatcher and Listener
 Publisher and Subscriber
 The core of the idea is that we completely
separate out event dispatch and event
handling.
 This is the best way to handle coupling
between objects.
Event Handler
 Event Handlers have a very simple
interface.
 One parameter represents the source of
the event
 The second represents state information.
 All objects in .NET extend from a class
called object.
 Polymorphism allows us to use that to deal
with event dispatch references.
public void Handle_Click (object sender, EventArgs e) {
}
Benefits of Separation
 Communication between objects without
hard-coded associations.
 Ensures cleanness of communication by virtue
of polymorphic interfaces.
 We know that we just need to deal with an
event object in our handler function.
 Scalable without adding complexity.
 Each component manages its own dispatching.
 Extensible
 We can easily add in our own events
 More on this in the next lecture
Benefits of the Delegate
Model
 One of the benefits of the delegate
model is that it allows new handlers to be
instantiated at runtime.
 Not possible in either Java or old versions of
.NET
 Handlers can be dynamically added or
removed while the program is running.
 Allowing for a very clean and efficient
implementation of dynamic delegate
dispatching.
Back to Design Patterns…
 You may find this event dispatch/handler method
referred to in the literature.
 It’s known as the observer design pattern.
 It has pretty wide applicability.
 Many languages use the observer patter in one
way or another.
 To add an extra level of complexity, the event
dispatch is often handled external.
 Objects indicate they wish to dispatch an event.
 The event dispatch thread handles the hard work.
Java Events
 The event model used within Java is
the delegation model.
 Objects are broken into two
categories:
 Event handlers
 Event dispatchers
 The event dispatcher is responsible for
informing all interested objects when
an event occurs.
 The event handler executes the code
that should be executed when the
event occurs.
Java Events
 Imagine if we wanted to trigger our own events.
 For example, a countdown timer that should call
an event when it hits zero.
 The clock itself is an event dispatcher.
 It has no code for handling the events.
 It has all the code for ensuring the events get called at
the correct time.
 Anything that was interested in catching this event
would be an event listener.
 It doesn’t administer the events, but contains the code
required for implementing the functionality.
 An event dispatcher may have many handlers.
Java Events
 We can use this same model for
dispatching other kinds of events.
 For example, we might want an action
event when the clock has finished
counting.
 We need to add a pair of add and
remove methods for the appropriate
listener.
 We also need a suitable data structure for
storing interested objects.
Java Events
 Often, we need nothing more
complicated than an ArrayList to store
listener objects.
 We need to ensure these methods are
thread-safe, which means using the
synchronised keyword.
 Don’t worry too much about this for now.
 We may return to this topic later on.
Java Events
ArrayList<ActionListener> myActionListeners;
public synchronized void addActionListener
(ActionListener ob) {
myActionListeners.add(ob);
}
public synchronized void removeActionListener
(ActionListener ob) {
myActionListeners.remove(ob);
}
Java Events
 We also need a method that handles calling
the appropriate handler on each object:
public void handleActionEvents() {
ActionEvent ex = new ActionEvent (this, 0, null);
ActionListener temp;
for (int i = 0; i < myActionListeners.size(); i++) {
temp = myActionListeners.get(i);
temp.actionPerformed (ex);
}
}
Java Events
 Now we can register an actionListener on
our this hypothetical clock just like we can
with a JButton.
 Except we have to provide the architecture
for handling it ourselves.
 Provided the handleActionEvents method
gets called at the right time, it’s all
Sunshine and Lollypops.
Summary
 Event handling in .NET is done using the
observer pattern.
 And through the mechanism of delegates
 There are several benefits that accrue
from this approach.
 It’s the cleanest way of allowing objects to
communicate.
 The best kind of coupling.
 Delegates are pretty powerful.

More Related Content

Similar to PATTERNS06 - The .NET Event Model (20)

PPTX
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016
DevOpsDays Tel Aviv
 
PPTX
ITE 1122_ Event Handling.pptx
udithaisur
 
PPTX
Programming Presentation by Lucky Bishwakarma
luckybishwakarma7676
 
PPT
Design Pattern with Actionscript
Daniel Swid
 
PDF
Dot NET Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
object oriented programming language in c++
Ravikant517175
 
PPT
Unit 6 Java
arnold 7490
 
PPT
Ch14
phanleson
 
PDF
Java Programming :Event Handling(Types of Events)
simmis5
 
PPTX
Software_Engineering_Presentation (1).pptx
ArifaMehreen1
 
DOCX
Sdlc
Bilal Aslam
 
DOCX
Sdlc
Bilal Aslam
 
PDF
Event driven application
Chris Saylor
 
PPTX
Android 101 Session @thejunction32
Eden Shochat
 
PDF
IoT in salsa Serverless
Massimo Bonanni
 
KEY
P106 rajagopalan-read
Takefumi MIYOSHI
 
PDF
Explore Event Driven Archtecture using PHP
NexGismo
 
PPTX
Guido schmutz-jax2011-event-driven soa
Guido Schmutz
 
PPT
lecture10-patterns.ppt
bryafaissal
 
PPT
lecture10-patterns.ppt
AnkitPangasa1
 
Event-driven Infrastructure - Mike Place, SaltStack - DevOpsDays Tel Aviv 2016
DevOpsDays Tel Aviv
 
ITE 1122_ Event Handling.pptx
udithaisur
 
Programming Presentation by Lucky Bishwakarma
luckybishwakarma7676
 
Design Pattern with Actionscript
Daniel Swid
 
Dot NET Interview Questions PDF By ScholarHat
Scholarhat
 
object oriented programming language in c++
Ravikant517175
 
Unit 6 Java
arnold 7490
 
Ch14
phanleson
 
Java Programming :Event Handling(Types of Events)
simmis5
 
Software_Engineering_Presentation (1).pptx
ArifaMehreen1
 
Event driven application
Chris Saylor
 
Android 101 Session @thejunction32
Eden Shochat
 
IoT in salsa Serverless
Massimo Bonanni
 
P106 rajagopalan-read
Takefumi MIYOSHI
 
Explore Event Driven Archtecture using PHP
NexGismo
 
Guido schmutz-jax2011-event-driven soa
Guido Schmutz
 
lecture10-patterns.ppt
bryafaissal
 
lecture10-patterns.ppt
AnkitPangasa1
 

More from Michael Heron (20)

PPTX
Meeple centred design - Board Game Accessibility
Michael Heron
 
PPTX
Musings on misconduct
Michael Heron
 
PDF
Accessibility Support with the ACCESS Framework
Michael Heron
 
PDF
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
PPTX
Authorship and Autership
Michael Heron
 
PDF
Text parser based interaction
Michael Heron
 
PPTX
SAD04 - Inheritance
Michael Heron
 
PPT
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
PPT
GRPHICS07 - Textures
Michael Heron
 
PPT
GRPHICS06 - Shading
Michael Heron
 
PPT
GRPHICS05 - Rendering (2)
Michael Heron
 
PPT
GRPHICS04 - Rendering (1)
Michael Heron
 
PPTX
GRPHICS03 - Graphical Representation
Michael Heron
 
PPTX
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
PPTX
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
PPT
GRPHICS09 - Art Appreciation
Michael Heron
 
PPTX
2CPP18 - Modifiers
Michael Heron
 
PPTX
2CPP17 - File IO
Michael Heron
 
PPT
2CPP16 - STL
Michael Heron
 
PPT
2CPP15 - Templates
Michael Heron
 
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Michael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
Authorship and Autership
Michael Heron
 
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
Michael Heron
 
GRPHICS05 - Rendering (2)
Michael Heron
 
GRPHICS04 - Rendering (1)
Michael Heron
 
GRPHICS03 - Graphical Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
Michael Heron
 
2CPP17 - File IO
Michael Heron
 
2CPP16 - STL
Michael Heron
 
2CPP15 - Templates
Michael Heron
 
Ad

Recently uploaded (20)

PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Ad

PATTERNS06 - The .NET Event Model

  • 2. Introduction  Event driven programming is a philosophy for building GUI applications.  Most modern programming languages incorporate a facility for event driven programming.  The mechanism by which events can be created and handled varies from language to language.  It tends to be markedly different in OO languages from non OO languages.  For the next few lectures, we are going to be looking at .NET.  Specifically, C#
  • 3. Event Driven Programming – In Brief  Console applications are system driven.  The user is just a puppet.  The flow of execution is with the computer.  Modern GUI based applications are user driven.  The computer is just a puppet.  The flow of execution is with the user.  This is reflected in a shift from processing intensive to interaction intensive applications.
  • 4. Process Intensive  Interaction is usually limited to prompts for information.  How many of these  For how long  Computer does large amounts of processing with relatively few configuration details.  Simulations  Complex AI routines  Batch processing
  • 5. Interaction Intensive  User drives the application.  Processing is usually short and focused.  Locus of control inverted from the Olden Days.  Focus is on user involvement in the process.  Word processors  Games  Pretty much any modern GUI application  Requires a new way of building programs.
  • 6. Event Driven Programming  In event driven programs, system driven by user interactions.  Click a button  Move a scrollbar  Type in a textbox  All interactions with a system component generate events.  Events contain information regarding the precise nature of the interaction
  • 7. Event Driven Programming  Each GUI component is responsible for dispatching information on events to interested parties.  Usually functions in a program.  Components hold an internal list of listeners.  Things that are listening for specific kind of events.  Each listener, or handler, is responsible for dealing with its response to the event occurring.
  • 8. Event Models – VB (Pre .NET)  Listener functions indicated by naming convention.  Function for deal with a click event on a control called cmdButton was called cmbButton_click.  Somewhat limited.  Stuck with predefined naming format.  No way for multiple functions to indicate an interest.  No longer the model used for VB in the .NET framework.
  • 9. Event Models - Java  Objects indicate their interest in an event by marking themselves as a listener.  Object oriented structure of the language allows for each listener to define the handler method.  Listeners defined by implementation of an interface  Correct methods indicated by naming convention.  actionPerformed for button clicks  adjustmentValueChanged for adjustment events  More flexible, but still somewhat clumsy.  One single method must manage events from many different components.
  • 10. Event Models - .NET  Components hold a list of delegates.  Each delegate contains a pointer to a function.  Direct mapping in .NET from event to delegates.  Delegates act as a wrapper around a function call.  Each component can have its own method.  Each component can handle multiple different listeners.  This is known as multicasting.  Best model so far?
  • 11. Event Driven Programming and OO  The event handler methods called when a method is fired get specifically configured objects as a parameter.  They hold the state information associated with the event.  These all stem from a common OO core  Polymorphism in Java permits compile time checking of event structure.  Delegate structure permits separation of abstraction and implementation.
  • 12. Delegates – The Basics  Works like a type safe function pointer.  A variable that acts as an invokeable reference to a function.  Delegates are objects.  Wrappers around the function pointer.  They provide a syntactically neat encapsulation of listener status.  And can be polymorphically assessed to ensure compile-time correction.
  • 13. Delegates in Actionusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { public delegate int HandleArithmetic (int num1, int num2); class Program { public static int addTwoNumbers(int num1, int num2) { return num1 + num2; } public static int multiplyTwoNumbers(int num1, int num2) { return num1 * num2; } static void Main(string[] args) { HandleArithmetic adding =new HandleArithmetic(addTwoNumbers); HandleArithmetic multiplying = new HandleArithmetic(multiplyTwoNumbers); Console.Out.WriteLine("Delegate one = " + adding(10, 20)); Console.Out.WriteLine("Delegate two = " + multiplying (10, 20)); Console.ReadLine(); } } }
  • 14. Delegates – The Basics  Delegates allow for the implementation of a syntactically safe callback.  Works on the Hollywood Principle  When attached to an event, they let us define a function stub that is called when specific processes are started / finished  Ideal mechanism for safely handling event invocation.
  • 15. Delegates – For Reals  Delegates are just a mechanism used for .NET event handling.  That’s not all they are.  You can think of a delegate as a combination of an object/method reference, and potentially a reference to another delegate.  Chain of command pattern.  Will invoke the next element in a chain when one exists.
  • 16. Delegates – For Reals  Small performance overhead associated with delegates.  Not as much as it used to be  Considerable leeway given for compile- time optimization.  This is a consequence of the very strict rules governing delegate construction.
  • 17. Delegates  Delegates get added directly to the event type of the component.  Delegates are usually an instance of the EventHandler class  Most of this is handled automatically for you in Visual Studio .NET: this.cmdButton.Click += new System.EventHandler (this.HandleClick)
  • 18. The Structure of Events in .NET  Different terminology is used here.  Consumer and Producer  Dispatcher and Listener  Publisher and Subscriber  The core of the idea is that we completely separate out event dispatch and event handling.  This is the best way to handle coupling between objects.
  • 19. Event Handler  Event Handlers have a very simple interface.  One parameter represents the source of the event  The second represents state information.  All objects in .NET extend from a class called object.  Polymorphism allows us to use that to deal with event dispatch references. public void Handle_Click (object sender, EventArgs e) { }
  • 20. Benefits of Separation  Communication between objects without hard-coded associations.  Ensures cleanness of communication by virtue of polymorphic interfaces.  We know that we just need to deal with an event object in our handler function.  Scalable without adding complexity.  Each component manages its own dispatching.  Extensible  We can easily add in our own events  More on this in the next lecture
  • 21. Benefits of the Delegate Model  One of the benefits of the delegate model is that it allows new handlers to be instantiated at runtime.  Not possible in either Java or old versions of .NET  Handlers can be dynamically added or removed while the program is running.  Allowing for a very clean and efficient implementation of dynamic delegate dispatching.
  • 22. Back to Design Patterns…  You may find this event dispatch/handler method referred to in the literature.  It’s known as the observer design pattern.  It has pretty wide applicability.  Many languages use the observer patter in one way or another.  To add an extra level of complexity, the event dispatch is often handled external.  Objects indicate they wish to dispatch an event.  The event dispatch thread handles the hard work.
  • 23. Java Events  The event model used within Java is the delegation model.  Objects are broken into two categories:  Event handlers  Event dispatchers  The event dispatcher is responsible for informing all interested objects when an event occurs.  The event handler executes the code that should be executed when the event occurs.
  • 24. Java Events  Imagine if we wanted to trigger our own events.  For example, a countdown timer that should call an event when it hits zero.  The clock itself is an event dispatcher.  It has no code for handling the events.  It has all the code for ensuring the events get called at the correct time.  Anything that was interested in catching this event would be an event listener.  It doesn’t administer the events, but contains the code required for implementing the functionality.  An event dispatcher may have many handlers.
  • 25. Java Events  We can use this same model for dispatching other kinds of events.  For example, we might want an action event when the clock has finished counting.  We need to add a pair of add and remove methods for the appropriate listener.  We also need a suitable data structure for storing interested objects.
  • 26. Java Events  Often, we need nothing more complicated than an ArrayList to store listener objects.  We need to ensure these methods are thread-safe, which means using the synchronised keyword.  Don’t worry too much about this for now.  We may return to this topic later on.
  • 27. Java Events ArrayList<ActionListener> myActionListeners; public synchronized void addActionListener (ActionListener ob) { myActionListeners.add(ob); } public synchronized void removeActionListener (ActionListener ob) { myActionListeners.remove(ob); }
  • 28. Java Events  We also need a method that handles calling the appropriate handler on each object: public void handleActionEvents() { ActionEvent ex = new ActionEvent (this, 0, null); ActionListener temp; for (int i = 0; i < myActionListeners.size(); i++) { temp = myActionListeners.get(i); temp.actionPerformed (ex); } }
  • 29. Java Events  Now we can register an actionListener on our this hypothetical clock just like we can with a JButton.  Except we have to provide the architecture for handling it ourselves.  Provided the handleActionEvents method gets called at the right time, it’s all Sunshine and Lollypops.
  • 30. Summary  Event handling in .NET is done using the observer pattern.  And through the mechanism of delegates  There are several benefits that accrue from this approach.  It’s the cleanest way of allowing objects to communicate.  The best kind of coupling.  Delegates are pretty powerful.