写代码的时候总会遇到一些,所为的“垃圾代码”,看起来就像一坨一坨的那啥一样。网上也有很多优化方案,但是似乎都不能很好的解决。今天群里有在讨论这个东西,突然灵感一现想到了一个应该是算得上不错的方案。我给它命名为——匹配模式
-
首先先看一下使用案例
public static void main(String[] args) {
Either.of(4)
.pattern(x->x==1,()-> System.out.println("值等与1"))
.pattern(x->x==2,()-> System.out.println("值等于2"))
.pattern(x->x==3,()-> System.out.println("值等于3"))
.matchOrElse(()-> System.out.println("啥也没匹配到"));
}
各位感觉如何。现在来看看如何实现的其实原理很简单。代码如下:
public class Either<T> {
private final T value;
private Pattern<T> head;
private Either(T value) {
this.value = value;
this.head=null;
}
private Either(T value,Pattern<T> head) {
this.value = value;
this.head=head;
}
public static <T> Either<T> of(T value) {
return new Either<>(value);
}
private static <T> Either<T> of(T value,Pattern<T> pattern) {
return new Either<>(value,pattern);
}
public Either<T> pattern(Predicate<T> predicate, Runnable runnable) {
Pattern<T> pattern=new Pattern<>(predicate,runnable);
if(head==null){
head=pattern;
}else {
Pattern next=head;
while (next.next!=null){
next=next.next;
}
next.next=pattern;
}
return this;
}
public <R>Either<R> map(Function<? super T,? extends R> mapper){
if(mapper==null) throw new NullPointerException();
return of(mapper.apply(value));
}
public <R>Either<R> flatMap(Function<? super T, Either<R>> mapper){
if(mapper==null) throw new NullPointerException();
return mapper.apply(value);
}
public void match() {
matchOrElse(null);
}
public void matchOrElse(Runnable orElse) {
if(head!=null){
head.test(value,orElse);
}
}
private static final class Pattern<T>{
private Predicate<T> predicate;
private Runnable runnable;
private Pattern<T> next;
private Pattern(Predicate<T> predicate, Runnable runnable) {
this.predicate = predicate;
this.runnable = runnable;
}
private void test(T value,Runnable orElse){
if(predicate.test(value)){
runnable.run();
}else {
if(next!=null){
next.test(value,orElse);
}else {
if(orElse!=null){
orElse.run();
}
}
}
}
}
}
以上代码都很简单,但是效果已经实现了,然也可以在此基础上随意扩展都是可行的。