added Callback pattern

This commit is contained in:
vehpsr
2015-03-26 22:47:04 +02:00
parent 33362d60ad
commit bf2df42c55
10 changed files with 140 additions and 2 deletions

View File

@ -0,0 +1,19 @@
package com.iluwatar;
/**
* Callback pattern is more native for dynamic languages where function are first-class citizen.
* Prior to Java8 can be simulated using simple (alike command) interfaces.
*/
public class App {
public static void main(String[] args) {
Task task = new SimpleTask();
Callback callback = new Callback() {
@Override
public void call() {
System.out.println("I'm done now.");
}
};
task.executeWith(callback);
}
}

View File

@ -0,0 +1,9 @@
package com.iluwatar;
/**
* Callback interface
*/
public interface Callback {
public void call();
}

View File

@ -0,0 +1,13 @@
package com.iluwatar;
/**
* Implementation of task that need to be executed
*/
public class SimpleTask extends Task {
@Override
public void execute() {
System.out.println("Perform some important activity.");
}
}

View File

@ -0,0 +1,16 @@
package com.iluwatar;
/**
* Template-method class for callback hook execution
*/
public abstract class Task {
public final void executeWith(Callback callback) {
execute();
if (callback != null) {
callback.call();
}
}
public abstract void execute();
}

View File

@ -0,0 +1,12 @@
package com.iluwatar;
import org.junit.Test;
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
}
}