package test;
import org.apache.commons.lang.StringUtils;
import java.util.Arrays;
import java.util.Iterator;
abstract class VolcanoNode {
protected VolcanoNode child;
public VolcanoNode() {
}
public VolcanoNode(VolcanoNode child) {
this.child = child;
}
abstract String next();
}
class Project extends VolcanoNode {
public Project(VolcanoNode child) {
super(child);
}
@Override
public String next() {
if (child != null) {
String nextString = child.next();
if (StringUtils.isNotEmpty(nextString)) {
return nextString.substring(1, nextString.length() - 1);
}
}
return null;
}
}
class Filter extends VolcanoNode {
public Filter(VolcanoNode child) {
super(child);
}
@Override
public String next() {
if (child != null) {
String nextString = child.next();
if (nextString != null) {
if (nextString.contains("hello")) {
return nextString;
} else {
return next();
}
}
}
return null;
}
}
class Scan extends VolcanoNode {
private final Iterator<String> iterator = Arrays.asList("hello volcano", "i am great").iterator();
public Scan() {
}
@Override
String next() {
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
}
}
public class TestVolcalo {
public static void main(String[] args) {
VolcanoNode root = new Project(new Filter(new Scan()));
System.out.println("Use volcano ---");
while (true) {
String str = root.next();
if (str != null) {
System.out.println(str);
} else {
break;
}
}
System.out.println("\nMock code generation ---");
Arrays.asList("hello volcano", "i am great").forEach(str -> {
if (str.contains("hello")) {
System.out.println(str.substring(1, str.length() - 1));
}
});
}
}
由此可见,Volcano模型虽然简化了计算模型,但是性能上通过代码生成可以有太大的提升。具体的代码生成技术原理可以参考这篇,那篇文章对Volcano模型还缺少一个最直观的说明,这里的代码能够帮助你建立概念。
再附上上面博客里GIF的分解,方便阅读。
图1
图2
图3
图4
图5
图6
图7
图8
图9
图10
图11
图12
图13
图14
图15
图16
图17
图18
等后面空了,在例子里再补上代码生成模型(不光是例子里的生成结果)的简单模拟。