Skip to content

Instantly share code, notes, and snippets.

@rac021
Created June 1, 2017 10:50
Show Gist options
  • Save rac021/db6e2edb9f2aa880da64b132ff565745 to your computer and use it in GitHub Desktop.
Save rac021/db6e2edb9f2aa880da64b132ff565745 to your computer and use it in GitHub Desktop.
package com.rac021.visitor ;
/**
*
* @author ryahiaoui
*/
import java.util.HashMap ;
import java.util.function.Function ;
public interface Visitor {
public interface Human { }
public class Child implements Human { }
public class Adult implements Human { }
public class Applier<R> {
private final HashMap< Class<?>, Function<Object, R>> map = new HashMap<>() ;
public <T> Applier<R> when(Class<T> type, Function< T, R > function ) {
map.put(type, obj -> function.apply(type.cast(obj))) ;
return this ;
}
public R call(Object receiver) {
return map.getOrDefault(receiver.getClass(),
obj -> { throw new IllegalArgumentException("Error " + obj); })
.apply(receiver) ;
}
}
public static void main(String[] args) {
Applier<String> applier = new Applier<>() ;
applier.when(Child.class, child -> " I'm a Child")
.when(Adult.class, adult -> "I'm an Adult") ;
Human human = new Child() ;
String who = applier.call(human) ;
System.out.println(who) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment