Skip to content

Instantly share code, notes, and snippets.

@CaglarGonul
Created April 10, 2013 14:42
Show Gist options
  • Save CaglarGonul/5355228 to your computer and use it in GitHub Desktop.
Save CaglarGonul/5355228 to your computer and use it in GitHub Desktop.
This time I understood what a closure is...
package com.fs;
public interface CallBack {
void m(int e);
}
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 removeCallBack(CallBack f){
if(cbs.contains(f)){
cbs.remove(f);
}
}
public void onAction(int i){
for (CallBack callBack : cbs) {
callBack.m(i);
}
}
}
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(){
CallBack cb1 = new CallBack() {
int x = 1;
@Override
public void m(int e) {
if(e==1){
System.out.println("You register this callback " + x + " time/times");
x++;
}
}
};
cb.registerCallBack(cb1);
cb.registerCallBack(cb1);
cb.registerCallBack(cb1);
cb.removeCallBack(cb1);
cb.onAction(1);
}
}
You register this callback 1 time/times
You register this callback 2 time/times
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment