Created
April 10, 2013 14:42
-
-
Save CaglarGonul/5355228 to your computer and use it in GitHub Desktop.
This time I understood what a closure is...
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 removeCallBack(CallBack f){ | |
if(cbs.contains(f)){ | |
cbs.remove(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(){ | |
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); | |
} | |
} |
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 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