我试图在Java中创建一个小型DSL,我可以使用它在数据库中填充testdata。我想使用的语言如下。
createRowInTableA().
createRowInTableB().
createRowInTableA().
createRowInTableB().
createRowInTableC().
end();
创建表的顺序很重要,例如tableB依赖于tableA,tableC依赖于tableA和tableB。因此,我想这样做,以便在创建tableA之后直接创建tableB的选项等。我已经开始创建描述DSL的接口但我不知道我应该如何实际实现接口以便使我正在寻找的嵌套行为的类型。这就是接口的样子。
public interface End {
public void sendTestData();
}
public interface TableA extends End {
public Builder createRowInTableA();
}
public interface TableB extends TableA {
public Builder createRowInTableB();
}
public interface TableC extends TableB {
public Builder createRowInTableC();
}
然而,当我开始使用构建器模式实现此语言来创建流畅的API时,我想要的层次结构就消失了。
public class DBBuilder implements TableC {
static class Builder {
public Builder createRowInTableA(){...}
public Builder createRowInTableB(){...}
public Builder createRowInTableC(){...}
}
}
答案 0 :(得分:0)
您可以使用一组接口和类适配器:
function submitForm() {
var fileList = document.getElementById("image").files;
var fileReader = new FileReader();
if (fileReader && fileList && fileList.length) {
fileReader.readAsArrayBuffer(fileList[0]);
fileReader.onload = function () {
var imageData = fileReader.result;
};
}
}
答案 1 :(得分:0)
这并不复杂。但我会检查是否有比使用流利的建设者更好的方法。例如,Java 8提供了闭包。希尔是我的建议。我没有编译和测试它。这个想法应该有效,但可能存在语法错误。
public class ABuilder
{
private BBuilder subBuilder;
public ABuilder()
{
subBuilder = new BBuilder(this);
}
public BBuilder createRowForA()
{
// your code
return this.subBuilder;
}
public void end()
{
// send test data
}
}
X
public class BBuilder
{
private ABuilder parentBuilder;
private CBuilder subBuilder;
public BBuilder( ABuilder parentBuilder )
{
this.parentBuilder = parentBuilder;
this.subBuilder = new CBuilder(this);
}
public CBuilder createRowForB()
{
// your code
return this.subBuilder;
}
public ABuilder end()
{
return this.parentBuilder;
}
}
X
public class CBuilder
{
private BBuilder parentBuilder;
public CBuilder( BBuilder parentBuilder )
{
this.parentBuilder = parentBuilder;
}
public CBuilder createRowForC()
{
// your code
// I Assume you want to be able to write more than 1 C-row
return this;
}
public BBuilder end()
{
return this.parentBuilder;
}
}
然后你可以这样做:
(new ABuilder())
.createRowForA()
.createRowForB()
.createRowForC()
.end()
.end()
.end();
(new ABuilder())
.createRowForA()
.createRowForB()
.end()
.createRowForB()
.createRowForC()
.end()
.end()
.end();
我确定你会看到更多的例子。 ; - )