SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
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/

Contenu connexe

Plus de Somenath Mukhopadhyay

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 bitsSomenath Mukhopadhyay
 
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...Somenath Mukhopadhyay
 
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 docsSomenath Mukhopadhyay
 
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 -...Somenath Mukhopadhyay
 
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...Somenath Mukhopadhyay
 
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 AndroidSomenath Mukhopadhyay
 
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...Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in JavaSomenath Mukhopadhyay
 
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 widgetsSomenath Mukhopadhyay
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
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 architectureSomenath Mukhopadhyay
 
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 patternSomenath Mukhopadhyay
 

Plus 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
 

Dernier

Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfInfopole1
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.IPLOOK Networks
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameKapil Thakar
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
Top 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTop 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTopCSSGallery
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1DianaGray10
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4DianaGray10
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kitJamie (Taka) Wang
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch TuesdayIvanti
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNeo4j
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveIES VE
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdfThe Good Food Institute
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024Brian Pichman
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxKaustubhBhavsar6
 

Dernier (20)

Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First Frame
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
Top 10 Squarespace Development Companies
Top 10 Squarespace Development CompaniesTop 10 Squarespace Development Companies
Top 10 Squarespace Development Companies
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kit
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch Tuesday
 
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through TokenizationStobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
Stobox 4: Revolutionizing Investment in Real-World Assets Through Tokenization
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4j
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024CyberSecurity - Computers In Libraries 2024
CyberSecurity - Computers In Libraries 2024
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptx
 

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/