SlideShare una empresa de Scribd logo
1 de 25
Descargar para leer sin conexión
Callback mechanisms using Function
Pointer (in C), Interface (in Java)
And EventListener Pattern
by
Somenath Mukhopadhyay
+91 9748185282
som@som-itsolutions.com
som.mukhopadhyay@gmail.com
Function Pointer
● Pointer is a variable that holds the address of
another data
● When we declare int func(), it implies that func
is kind of constant pointer to a method
● Can't we declare a non-const pointer to a
method???
Function Pointer
● Yes we can declare a non-const pointer to a
function as the following
int (*ptrFunc) ()
– It implies that ptrFunc is a pointer to a function
which takes no parameter and return an integer
Normal Function
● #include<stdio.h>
● /* function prototype */
● int func(int, int);
● int main(void)
● {
● int result;
● /* calling a function named func */
● result = func(10,20);
● printf("result = %dn",result);
● return 0;
● }
● /* func definition goes here */
● int func(int x, int y)
● {
● return x+y;
● }
Function Pointer
● #include<stdio.h>
● int func(int, int);
● int main(void)
● {
● int result1,result2;
● /* declaring a pointer to a function which takes
● two int arguments and returns an integer as result */
● int (*ptrFunc)(int,int);
● /* assigning ptrFunc to func's address */
● ptrFunc=func;
● /* calling func() through explicit dereference */
● result1 = (*ptrFunc)(10,20);
● /* calling func() through implicit dereference */
● result2 = ptrFunc(10,20);
● printf("result1 = %d result2 = %dn",result1,result2);
● return 0;
● }
● int func(int x, int y)
● {
● return x+y;
● }
Callback
● In computer programming, a callback is a
reference to executable code, or a piece of
executable code, that is passed as an
argument to other code. This allows a lower-
level software layer to call a subroutine (or
function) defined in a higher-level layer.”
(Source : Wikipedia)
● In other words, Callback is the way through
which we pass a function pointer to a code from
where we want our callback/handler to be
called.
Callback
● Callback mechanism is heavily used in
Asynchronous programming. Its basic purpose
is to notify the caller when the callee has
finished some job
● So the caller called upon the callee and then
does not block until the callee finishes the task.
● When the callee finishes its task, it notifies the
caller and then the caller gets back the result.
Example of Callback (in C)
/* callback.c */
●
#include<stdio.h>
●
#include"reg_callback.h"
●
/* callback function definition goes here */
● void my_callback(void)
●
{
●
printf("inside my_callbackn");
●
}
● int main(void)
●
{
●
/* initialize function pointer to
●
my_callback */
● callback ptr_my_callback=my_callback;
●
printf("This is a program demonstrating function callbackn");
●
/* register our callback function */
●
register_callback(ptr_my_callback);
●
printf("back inside main programn");
●
return 0;
●
}
Callback - Example
● /* reg_callback.h */
● typedef void (*callback)(void);
● void register_callback(callback ptr_reg_callback);
Callback - Example
● /* reg_callback.c */
● #include<stdio.h>
● #include"reg_callback.h"
● /* registration goes here */
● void register_callback(callback ptr_reg_callback)
● {
● printf("inside register_callbackn");
● /* calling our callback function my_callback */
● (*ptr_reg_callback)();
● }
Callback - Example
Result of the previous example
● This is a program demonstrating function callback
● inside register_callback
● inside my_callback
● back inside main program
Callback in Java – Using Interface
● Java does not have the concept of function
pointer
● It implements Callback mechanism through its
Interface mechanism
● Here instead of a function pointer, we declare
an Interface having a method which will be
called when the callee finishes its task
Callback in Java – Using Interface
public interface Callback
● {
● public void notify(Result result);
● }
Callback in Java – Using Interface
public Class Caller implements Callback
● {
Callee ce = new Callee(this);
– //Other functionality
//Call the Asynctask
ce.doAsynctask();//pass self to the callee
● public void notify(Result result){
//Got the result after the callee has finished the task
//Can do whatever i want with the result
● }
● }
Callback in Java – Using Interface
public Class Callee {
● Callback cb;
● Callee(Callback cb){
– this.cb = cb;
● }
● doAsynctask(){
● //do the long running task
● //get the result
● cb.notify(result);//after the task is completed, notify the
caller
● }
● }
EventListener/Observer
● This pattern is used to notify 0 to n numbers of
Observers/Listeners that a particular task has
finished
● The difference between Callback mechanism
and EventListener/Observer mechanism is that
in callback, the callee notifies the single caller,
whereas in Eventlisener/Observer, the callee
can notify anyone who is interested in that
event (the notification may go to some other
parts of the application which has not triggered
the task)
EventListener
● //public interface Events {
●
● public void clickEvent();
● public void longClickEvent();
● }
Widget
● See the following link
SourceCode_Of_Widget
(https://docs.google.com/document/d/18dTyRas
JF3698XQA909ozgkmWIxd6pYqbibOlqfzDW0/
edit?usp=sharing)
Button Class
public class Button extends Widget{
● private String mButtonText;
● public Button () { }
● public String getButtonText() {
● return mButtonText;}
● public void setButtonText(String buttonText) {
● this.mButtonText = buttonText;}
● }
CheckBox Class
public class CheckBox extends Widget{
● private boolean checked;
● public CheckBox() {
● checked = false;}
● public boolean isChecked(){
● return (checked == true);}
● public void setCheck(boolean checked){
● this.checked = checked;}
● }
Activity Class
● See the source code
● Activity-Class Source Code
● (https://docs.google.com/document/d/18dTyRas
JF3698XQA909ozgkmWIxd6pYqbibOlqfzDW0/
edit?usp=sharing)
Other Class
public class OtherClass implements Widget.OnClickEventListener{
● Button mButton;
● public OtherClass(){
● mButton = Activity.getActivityHandle().mButton;
● mButton.setOnClickEventListner(this);
● }
● @Override
● public void onClick(Widget source) {
● if(source == mButton){
● System.out.println("Other Class has also received the event
notification...");
● }
● }
●
Main Class
public class Main {
● public static void main(String[] args) {
● // TODO Auto-generated method stub
● Activity a = new Activity();
● OtherClass o = new OtherClass();
● a.doSomeWork(a.mButton);
● a.doSomeWork(a.mCheckBox);
● }
● }
Explanation
As you can see that the OtherClass is also
interested in the Click event of the Button inside
the Activity. The Activity is responsible for the
Button's click event. But alongwith the Activity
(the Caller) the other parts of the Application
(i.e. OtherClass) is also able to get this
notification. This is one of the main
significances of EventListener/Observer
pattern.
Thank You!!!
● Get the source code from
https://github.com/sommukhopadhyay/EventListenerExample
● Reference : http://opensourceforu.com/2012/02/function-pointers-
and-callbacks-in-c-an-odyssey/

Más contenido relacionado

Más de Somenath Mukhopadhyay

Más de Somenath Mukhopadhyay (20)

Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bits
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Uml training
Uml trainingUml training
Uml training
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
 
Android services internals
Android services internalsAndroid services internals
Android services internals
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Bridge Pattern
Bridge PatternBridge Pattern
Bridge Pattern
 
Test Driven Development and JUnit
Test Driven Development and JUnitTest Driven Development and JUnit
Test Driven Development and JUnit
 
WiFi Security Explained
WiFi Security ExplainedWiFi Security Explained
WiFi Security Explained
 
Thin Template Explained
Thin Template ExplainedThin Template Explained
Thin Template Explained
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Different ways of Callback Mechanism and EventListener Pattern

  • 1. Callback mechanisms using Function Pointer (in C), Interface (in Java) And EventListener Pattern by Somenath Mukhopadhyay +91 9748185282 som@som-itsolutions.com som.mukhopadhyay@gmail.com
  • 2. Function Pointer ● Pointer is a variable that holds the address of another data ● When we declare int func(), it implies that func is kind of constant pointer to a method ● Can't we declare a non-const pointer to a method???
  • 3. Function Pointer ● Yes we can declare a non-const pointer to a function as the following int (*ptrFunc) () – It implies that ptrFunc is a pointer to a function which takes no parameter and return an integer
  • 4. Normal Function ● #include<stdio.h> ● /* function prototype */ ● int func(int, int); ● int main(void) ● { ● int result; ● /* calling a function named func */ ● result = func(10,20); ● printf("result = %dn",result); ● return 0; ● } ● /* func definition goes here */ ● int func(int x, int y) ● { ● return x+y; ● }
  • 5. Function Pointer ● #include<stdio.h> ● int func(int, int); ● int main(void) ● { ● int result1,result2; ● /* declaring a pointer to a function which takes ● two int arguments and returns an integer as result */ ● int (*ptrFunc)(int,int); ● /* assigning ptrFunc to func's address */ ● ptrFunc=func; ● /* calling func() through explicit dereference */ ● result1 = (*ptrFunc)(10,20); ● /* calling func() through implicit dereference */ ● result2 = ptrFunc(10,20); ● printf("result1 = %d result2 = %dn",result1,result2); ● return 0; ● } ● int func(int x, int y) ● { ● return x+y; ● }
  • 6. Callback ● In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower- level software layer to call a subroutine (or function) defined in a higher-level layer.” (Source : Wikipedia) ● In other words, Callback is the way through which we pass a function pointer to a code from where we want our callback/handler to be called.
  • 7. Callback ● Callback mechanism is heavily used in Asynchronous programming. Its basic purpose is to notify the caller when the callee has finished some job ● So the caller called upon the callee and then does not block until the callee finishes the task. ● When the callee finishes its task, it notifies the caller and then the caller gets back the result.
  • 8. Example of Callback (in C) /* callback.c */ ● #include<stdio.h> ● #include"reg_callback.h" ● /* callback function definition goes here */ ● void my_callback(void) ● { ● printf("inside my_callbackn"); ● } ● int main(void) ● { ● /* initialize function pointer to ● my_callback */ ● callback ptr_my_callback=my_callback; ● printf("This is a program demonstrating function callbackn"); ● /* register our callback function */ ● register_callback(ptr_my_callback); ● printf("back inside main programn"); ● return 0; ● }
  • 9. Callback - Example ● /* reg_callback.h */ ● typedef void (*callback)(void); ● void register_callback(callback ptr_reg_callback);
  • 10. Callback - Example ● /* reg_callback.c */ ● #include<stdio.h> ● #include"reg_callback.h" ● /* registration goes here */ ● void register_callback(callback ptr_reg_callback) ● { ● printf("inside register_callbackn"); ● /* calling our callback function my_callback */ ● (*ptr_reg_callback)(); ● }
  • 11. Callback - Example Result of the previous example ● This is a program demonstrating function callback ● inside register_callback ● inside my_callback ● back inside main program
  • 12. Callback in Java – Using Interface ● Java does not have the concept of function pointer ● It implements Callback mechanism through its Interface mechanism ● Here instead of a function pointer, we declare an Interface having a method which will be called when the callee finishes its task
  • 13. Callback in Java – Using Interface public interface Callback ● { ● public void notify(Result result); ● }
  • 14. Callback in Java – Using Interface public Class Caller implements Callback ● { Callee ce = new Callee(this); – //Other functionality //Call the Asynctask ce.doAsynctask();//pass self to the callee ● public void notify(Result result){ //Got the result after the callee has finished the task //Can do whatever i want with the result ● } ● }
  • 15. Callback in Java – Using Interface public Class Callee { ● Callback cb; ● Callee(Callback cb){ – this.cb = cb; ● } ● doAsynctask(){ ● //do the long running task ● //get the result ● cb.notify(result);//after the task is completed, notify the caller ● } ● }
  • 16. EventListener/Observer ● This pattern is used to notify 0 to n numbers of Observers/Listeners that a particular task has finished ● The difference between Callback mechanism and EventListener/Observer mechanism is that in callback, the callee notifies the single caller, whereas in Eventlisener/Observer, the callee can notify anyone who is interested in that event (the notification may go to some other parts of the application which has not triggered the task)
  • 17. EventListener ● //public interface Events { ● ● public void clickEvent(); ● public void longClickEvent(); ● }
  • 18. Widget ● See the following link SourceCode_Of_Widget (https://docs.google.com/document/d/18dTyRas JF3698XQA909ozgkmWIxd6pYqbibOlqfzDW0/ edit?usp=sharing)
  • 19. Button Class public class Button extends Widget{ ● private String mButtonText; ● public Button () { } ● public String getButtonText() { ● return mButtonText;} ● public void setButtonText(String buttonText) { ● this.mButtonText = buttonText;} ● }
  • 20. CheckBox Class public class CheckBox extends Widget{ ● private boolean checked; ● public CheckBox() { ● checked = false;} ● public boolean isChecked(){ ● return (checked == true);} ● public void setCheck(boolean checked){ ● this.checked = checked;} ● }
  • 21. Activity Class ● See the source code ● Activity-Class Source Code ● (https://docs.google.com/document/d/18dTyRas JF3698XQA909ozgkmWIxd6pYqbibOlqfzDW0/ edit?usp=sharing)
  • 22. Other Class public class OtherClass implements Widget.OnClickEventListener{ ● Button mButton; ● public OtherClass(){ ● mButton = Activity.getActivityHandle().mButton; ● mButton.setOnClickEventListner(this); ● } ● @Override ● public void onClick(Widget source) { ● if(source == mButton){ ● System.out.println("Other Class has also received the event notification..."); ● } ● } ●
  • 23. Main Class public class Main { ● public static void main(String[] args) { ● // TODO Auto-generated method stub ● Activity a = new Activity(); ● OtherClass o = new OtherClass(); ● a.doSomeWork(a.mButton); ● a.doSomeWork(a.mCheckBox); ● } ● }
  • 24. Explanation As you can see that the OtherClass is also interested in the Click event of the Button inside the Activity. The Activity is responsible for the Button's click event. But alongwith the Activity (the Caller) the other parts of the Application (i.e. OtherClass) is also able to get this notification. This is one of the main significances of EventListener/Observer pattern.
  • 25. Thank You!!! ● Get the source code from https://github.com/sommukhopadhyay/EventListenerExample ● Reference : http://opensourceforu.com/2012/02/function-pointers- and-callbacks-in-c-an-odyssey/