Last active
June 26, 2017 09:20
-
-
Save lonelyleaf/afedfb72f490bd604f2a06afea1764fa to your computer and use it in GitHub Desktop.
to replace the fucking swith in java,reduce the code lines
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
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* replace | |
* Created by Rock on 2017/6/26. | |
*/ | |
public class Switcher<T> { | |
private Map<T, Consumer<T>> mapper = new HashMap<>(); | |
private Consumer defaults; | |
public Switcher<T> cases(T s, Consumer<T> consumer) { | |
mapper.put(s, consumer); | |
return this; | |
} | |
public Switcher<T> defaults(Consumer<T> consumer){ | |
this.defaults = consumer; | |
return this; | |
} | |
public void trigger(T s) { | |
if (!mapper.containsKey(s) && defaults!=null){ | |
defaults.call(s); | |
return; | |
} | |
Consumer consumer = mapper.get(s); | |
if (consumer != null) { | |
consumer.call(s); | |
} | |
} | |
public interface Consumer<T> { | |
void call(T s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
use like this