Created
August 15, 2017 12:16
-
-
Save Dantali0n/0338ff14e03d54859ab3f33e8a4e66c4 to your computer and use it in GitHub Desktop.
C++ Delegation in A java type fashion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "exampleclass.h" | |
/** | |
* Assign instance of delegate upon object construction, do not allow serialCommand to exist without a delegate object | |
*/ | |
ExampleClass::ExampleClass(ExampleClassDelegate *eventHandler) { | |
this->eventHandler = eventHandler; // assign the delegate | |
} | |
// example function to see how calls inside of ExampleClass can reach code outside of ExampleClass | |
// through the instance of eventHandler/ | |
ExampleClass::exampleFunction() { | |
eventHandler.eventExample(); // call eventExample to the outside of ExampleClass defined instance of ExampleClassDelegate | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Abstract delegate to allow outside of SerialCommand processing of events | |
*/ | |
class ExampleClassDelegate { | |
public: | |
virtual void eventExample() = 0; | |
}; | |
class ExampleClass { | |
private: | |
ExampleClassDelegate *eventHandler; | |
public: | |
ExampleClass(ExampleClassDelegate *eventHandler); | |
void exampleFunction(); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "exampleclass.h" | |
/** | |
* Implementation | |
*/ | |
class ExampleClassDelegateImplementation: public ExampleClassDelegate { | |
void eventExample() { | |
// Code called from within ExampleCLass that is defined at a later time outside of ExampleClass | |
// allowing for event like behavior | |
} | |
}; | |
ExampleClassDelegateImplementation serialCommandDelegate = ExampleClassDelegateImplementation(); | |
ExampleClass exampleClass = ExampleClass(&serialCommandDelegate); | |
void setup() { | |
// sets of the chain of events. | |
// 1: ExampleClass::exampleFunction() | |
// 2: eventHandler.eventExample() | |
// 3: ExampleClassDelegateImplementation::eventExample() | |
exampleClass.exampleFunction(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment