Delegates and Events 14: Delegates and Events

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Written by: Dr. JJ Shepherd
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Programming Based on Events
Class. 2 Objectives Discuss class basics –fields –methods –access levels Present object creation –new operator.
OCT 1 Master of Information System Management Organizational Communications and Distributed Object Technologies Lecture 5: Distributed Objects.
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Writing Classes (Chapter 4)
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
ECE122 Feb. 22, Any question on Vehicle sample code?
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Object Oriented Programming.  Interface  Event Handling.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
Introduction to Object-Oriented Programming Lesson 2.
From C++ to C# Part 5. Enums Similar to C++ Similar to C++ Read up section 1.10 of Spec. Read up section 1.10 of Spec.
Events Programming in C# Events CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Classes - Intermediate
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
CIS NET Applications1 Chapter 6 – Events. CIS NET Applications2 Objectives Delegate-based Events.NET event support Practical guides for managing.
Unit 2. Constructors It initializes an object when it is created. It has same as its class and syntactically similar to a method. Constructor have no.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Memory Management.
C# for C++ Programmers 1.
INF230 Basics in C# Programming
Classes and Objects.
Chapter 7: User-Defined Functions II
16: Equals Equals Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
2.7 Inheritance Types of inheritance
Java Primer 1: Types, Classes and Operators
Methods Attributes Method Modifiers ‘static’
Chapter 3: Using Methods, Classes, and Objects
Chapter Eleven Handling Events.
Review Session.
Lecture 14 Writing Classes part 2 Richard Gesick.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
C# Event Processing Model
6 Delegate and Lambda Expressions
Properties 7: Properties Programming C# © 2003 DevelopMentor, Inc.
Classes, Encapsulation, Methods and Constructors (Continued)
Learning Objectives Classes Constructors Principles of OOP
Delegates & Events 1.
Lesson 7. Events, Delegates, Generics.
CIS 199 Final Review.
Class.
Interface 11: Interface Programming C# © 2003 DevelopMentor, Inc.
CMSC 202 Exceptions.
Corresponds with Chapter 5
Creating and Using Classes
Events, Delegates, and Lambdas
Presentation transcript:

Delegates and Events 14: Delegates and Events Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Objectives Introduce delegates and events defining delegate types invoking through delegates registering multiple targets Discuss design benefits of using delegates Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

State Objects typically maintain state state changes over time 14: Delegates and Events State Objects typically maintain state state changes over time class Student { string name; double gpa; int units; public void RecordClass(int grade) gpa = (gpa * units + grade) / (units + 1); units++; } ... store state change state Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Notification May want to notify interested parties of state change 14: Delegates and Events Notification May want to notify interested parties of state change notification widely used throughout .NET framework user interface event handling most common example Parent RecordClass Student Registrar new grade causes gpa to change notify Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Pattern Notification typically involves registration and callback 14: Delegates and Events Pattern Notification typically involves registration and callback target registers with caller caller calls back target when state changes pattern also called publish/subscribe Student (caller) Parent (target) register callback Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

14: Delegates and Events Delegates .NET Framework uses delegates to implement callbacks intermediary between caller and target declaration defines callback method signature instance stores object reference and method token caller target object target method callback delegate callback Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Information flow delegate 14: Delegates and Events Information flow Caller and target need to agree on information flow data passed through delegate Student Parent object Parent method double delegate double void void Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Delegate definition Define delegate with delegate keyword 14: Delegates and Events Delegate definition Define delegate with delegate keyword syntax similar to method declaration without body delegate name placed where method name usually goes delegate keyword name of delegate delegate void StudentCallback(double gpa); target method return type target method parameter Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Delegate as type Delegate name is type name can declare references 14: Delegates and Events Delegate as type Delegate name is type name can declare references can create objects define delegate delegate void StudentCallback(double gpa); StudentCallback a = new StudentCallback(...); reference object Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

14: Delegates and Events Target use of delegate Target defines method with signature specified by delegate parameters and return type must match method name not constrained delegate defines required signature delegate void StudentCallback(double gpa); target class Parent { public void Report(double gpa) ... } method signature matches delegate Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Caller use of delegate Caller typically defines delegate reference 14: Delegates and Events Caller use of delegate Caller typically defines delegate reference caller class Student { public StudentCallback GpaChanged; ... } delegate reference Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Registration Create delegate object and store in caller to register 14: Delegates and Events Registration Create delegate object and store in caller to register pass target object and method to delegate constructor void Run() { Student ann = new Student("Ann"); Parent mom = new Parent(); StudentCallback a = new StudentCallback(mom.Report); ann.GpaChanged = a; ... } caller target create store target object target method Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Invocation Caller invokes callback indirectly through delegate 14: Delegates and Events Invocation Caller invokes callback indirectly through delegate uses method call syntax on delegate delegate calls target method on target object class Student { public StudentCallback GpaChanged; public void RecordClass(int grade) // update gpa ... GpaChanged(gpa); } invoke callback through delegate callback takes double argument Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Summary of delegate use 14: Delegates and Events Summary of delegate use define delegate delegate void StudentCallback(double gpa); class Parent { public void Report(double gpa) { ... } } class Student public StudentCallback GpaChanged; public void RecordClass(int grade) // update gpa ... GpaChanged(gpa); target method caller stores delegate caller invokes delegate Student ann = new Student("Ann"); Parent mom = new Parent(); ann.GpaChanged = new StudentCallback(mom.Report); ann.RecordClass(4); // 4 == 'A' create and install delegate Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Null reference Delegate is reference type 14: Delegates and Events Null reference Delegate is reference type defaults to null when used as field typical to guard invocation class Student { public StudentCallback GpaChanged; public void RecordClass(int grade) // update gpa ... if (GpaChanged != null) GpaChanged(gpa); } test before call Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Static methods Static method may be target of delegate 14: Delegates and Events Static methods Static method may be target of delegate use class name and method name when creating delegate no object specified since no this object associated with call class Registrar { public static void Log(double gpa) ... } static method void Run() { Student ann = new Student("Ann"); ann.GpaChanged = new StudentCallback(Registrar.Log); ... } register Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Multiple targets Can combine delegates using operator+= or operator+ 14: Delegates and Events Multiple targets Can combine delegates using operator+= or operator+ creates invocation list of delegates all targets called when delegate invoked targets called in order added use of += ok even when left-hand-side is null Parent mom = new Parent(); Parent dad = new Parent(); Student ann = new Student("Ann"); ann.GpaChanged += new StudentCallback(mom.Report); ann.GpaChanged += new StudentCallback(dad.Report); ... targets first second Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Remove delegate Can remove delegate from invocation list 14: Delegates and Events Remove delegate Can remove delegate from invocation list use operator-= or operator- identity of target object/method determines which is removed Parent mom = new Parent(); Parent dad = new Parent(); Student ann = new Student("Ann"); ann.GpaChanged += new StudentCallback(mom.Report); ann.GpaChanged += new StudentCallback(dad.Report); ... ann.GpaChanged -= new StudentCallback(dad.Report); add remove Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Public delegate Not common to have public delegate field 14: Delegates and Events Public delegate Not common to have public delegate field allows assignment: could overwrite existing registrants allows external invocation: decision should be made internally class Student { public StudentCallback GpaChanged; ... } public delegate Parent mom = new Parent(); Parent dad = new Parent(); Student ann = new Student("Ann"); ... ann.GpaChanged = new StudentCallback(mom.Report); ann.GpaChanged = new StudentCallback(dad.Report); ann.GpaChanged(4.0); overwrite mom handler invoke Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Events Events give private data/public accessor pattern for delegates 14: Delegates and Events Events Events give private data/public accessor pattern for delegates created by applying event keyword to delegate external code can uses += and -= no external assignment or invocation class Student { public event StudentCallback GpaChanged; ... } event Parent mom = new Parent(); Student ann = new Student("Ann"); ann.GpaChanged += new StudentCallback(mom.Report); ann.GpaChanged = new StudentCallback(mom.Report); ann.GpaChanged(4.0); ... ok to use += error to use = error to invoke Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Design delegate Delegates provide clean way to code publish/subscribe 14: Delegates and Events Design Delegates provide clean way to code publish/subscribe publisher independent of type of subscriber publisher independent of target method name subscriber constrained only by callback method signature promotes loosely coupled designs Publisher Subscriber target method publish delegate publish Programming C# © 2003 DevelopMentor, Inc. 12/1/2003

Summary Delegates are objects that invoke methods on other objects 14: Delegates and Events Summary Delegates are objects that invoke methods on other objects useful to implement callbacks Events add semantic/syntactic layer to delegates enforce clean and safe registration/deregistration protocols Programming C# © 2003 DevelopMentor, Inc. 12/1/2003