package callback;
public interface CallBack {
void execute();
}
package callback;
public class MyCallBack implements CallBack {
@Override
public void execute() {
testMethod();
}
public static void testMethod(){
for (int i= 0 ; i< 100000000 ; i++){
}
}
}
package callback;
// 代理类
public class Proxy implements CallBack {
private MyCallBack callBack;
public Proxy(MyCallBack callBack) {
this.callBack = callBack;
}
@Override
public void execute() {
callBack.execute();
}
}
package callback;
public class RunningTime {
public static void testMethod(){
for (int i = 0; i < 100000; ++i) {
System.out.print("i:" + i);
}
System.out.println();
}
public void testTime() {
long begin = System.currentTimeMillis();
testMethod();
long end = System.currentTimeMillis();
System.out.println("cost time:" + (end - begin));
}
public static void main(String[] args) {
RunningTime test = new RunningTime();
test.testTime();
System.out.println("ok");
}
}
package callback;
public class Tools {
public void testTime (CallBack callBack) {
long start = System.currentTimeMillis();
callBack.execute();
long end = System.currentTimeMillis();
System.out.println("cost time: " + (end - start));
}
public static void main(String[] args) throws InterruptedException {
/**Tools tools = new Tools();
tools.testTime(() -> RunningTime.testMethod()); // n=100执行时间9ms,时间长之后近似
Thread.sleep(1000);
tools.testTime(new CallBack() { // n=100 cost 2ms
@Override
public void execute() {
RunningTime.testMethod();
}
});
System.out.println("hhh, ok!");**/
Tools tools = new Tools();
// 代理类实现调用
Proxy proxy = new Proxy(new MyCallBack());
tools.testTime(proxy);
}
}
区别:
1 代理模式需要创建接口实现类,并放入代理类中隔离性能好,扩展性好。
2 回调函数不需要创建接口实现类, 编写方便。
网友评论