Last active
December 15, 2015 20:49
-
-
Save CaglarGonul/5321488 to your computer and use it in GitHub Desktop.
Callback implementation in Java7
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
package com.fs; | |
public interface CallBack { | |
void m(int e); | |
} |
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
package com.impl.callback; | |
import com.fs.CallBack; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class CCallBack { | |
List<CallBack> cbs = new ArrayList<>(); | |
public void registerCallBack(CallBack f){ | |
cbs.add(f); | |
} | |
public void onAction(int i){ | |
for (CallBack callBack : cbs) { | |
callBack.m(i); | |
} | |
} | |
} |
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
package basic; | |
import com.fs.CallBack; | |
import com.impl.callback.CCallBack; | |
import org.junit.Test; | |
public class CallBackTester { | |
CCallBack cb = new CCallBack(); | |
@Test | |
public void test_callback(){ | |
//Add callback for pressing 1 | |
CallBack cb1 = new CallBack() { | |
@Override | |
public void m(int e) { | |
if(e==1){ | |
System.out.println("You pressed 1."); | |
} | |
} | |
}; | |
cb.registerCallBack(cb1); | |
//Add callback for pressing 2 | |
CallBack cb2 = new CallBack() { | |
@Override | |
public void m(int e) { | |
if(e==2){ | |
System.out.println("You pressed 2."); | |
} | |
} | |
}; | |
cb.registerCallBack(cb2); | |
//Add callback for pressing 3 | |
CallBack cb3 = new CallBack() { | |
@Override | |
public void m(int e) { | |
if(e==3){ | |
System.out.println("You pressed 3."); | |
} | |
} | |
}; | |
cb.registerCallBack(cb3); | |
//Add callback for pressing 3 again | |
cb.registerCallBack(cb3); | |
//Lets press 3 | |
cb.onAction(3); | |
} | |
} |
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
You pressed 3. | |
You pressed 3. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment