使用宿主語言(Java)語法構建領域專用語言,通過方法鏈與靜態導入實現接近自然語言的可讀性。
Graph().edge().from("a").to("b").weight(20.0)
.edge().from("b").to("c").weight(10.0)
.printGraph();
GraphBuilderpublic class GraphBuilder {
private final Graph graph = new Graph();
private GraphBuilder() {}
public static GraphBuilder Graph() { return new GraphBuilder(); }
public EdgeBuilder edge() { return new EdgeBuilder(graph); }
public void printGraph() { graph.print(); }
}
EdgeBuilder(鏈式核心)public class EdgeBuilder {
private final Graph graph;
private String from, to;
private Double weight;
public EdgeBuilder(Graph graph) { this.graph = graph; }
public EdgeBuilder from(String v) { this.from = v; return this; }
public EdgeBuilder to(String v) { this.to = v; return this; }
public EdgeBuilder weight(double w) { this.weight = w; return this; }
/** 終結當前邊,加入圖並回傳自身以支援連續 .edge() */
public EdgeBuilder build() {
graph.addEdge(from, to, weight);
return this;
}
}
Graph、Vertex、Edgepublic class Graph {
private final Map vertices = new HashMap<>();
private final List edges = new ArrayList<>();
public void addEdge(String from, String to, Double w) {
Vertex f = vertices.computeIfAbsent(from, Vertex::new);
Vertex t = vertices.computeIfAbsent(to, Vertex::new);
edges.add(new Edge(f, t, w));
}
public void print() { edges.forEach(System.out::println); }
}
public class Vertex { private final String label; /* getter */ }
public class Edge { private Vertex from, to; private Double weight; /* getter/toString */ }
| 模式 | 應用 |
|---|---|
| Builder / Fluent API | EdgeBuilder 方法鏈構建邊屬性 |
| Method Chaining | 每個 setter 回傳 this |
| Static Factory | Graph() 入口方法 |
| Context Object | GraphBuilder 持有 Graph 上下文 |
.vertex("a").label("Node A").color("red").edge().from("a").to("b").when(condition).export(DOT).toFile("g.dot")GraphBuilder<V, E> 限制頂點/邊類型when(mock.foo()).thenReturn(bar)assertThat(list).hasSize(3).contains("a")