Java 8的內部DSL

banq發表於2013-06-03
DSL定義:Domain-specific language (名詞,簡稱DSL): 是一種專注特定領域的有限表達法。

Martin Fowler 認為DSL區別於通常語義上的領域模型,透過一些內部的DSL表示式可以匯入或構建領域模型。(DSL類似領域模型的Builder)。

這種內部DSL表示式有下面幾種:
1. Method Chaining 方法鏈 Fluent Style流暢風格
2. Functional Sequence
3. Nested Functions 巢狀函式
4.Lambda Expressions/Closures

在Java 8中建立Martin Fowler的內部DSL Creating Internal DSLs in Java, Java 8- Adopting Martin Fowler’s approach | Java, JVM and beyond
一文以Java 8為例說明了這種內部表示式的使用。

下面以三個語義模型為例:
Graph

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
 
public class Graph {
 
  private List<Edge> edges;
  private Set<Vertex> vertices;
 
  public Graph() {
    edges = new ArrayList<>();
    vertices = new TreeSet<>();
  }
  public void addEdge(Edge edge){
    getEdges().add(edge);
  }
   
  public void addVertice(Vertex v){
    getVertices().add(v);
  }
 
  public List<Edge> getEdges() {
    return edges;
  }
 
  public Set<Vertex> getVertices() {
    return vertices;
  }
   
  public static void printGraph(Graph g){
    System.out.println("Vertices...");
    for (Vertex v : g.getVertices()) {
      System.out.print(v.getLabel() + " ");
    }
    System.out.println("");
    System.out.println("Edges...");
    for (Edge e : g.getEdges()) {
      System.out.println(e);
    }
  }
}
<p class="indent">


Edge.java

public class Edge {
  private Vertex fromVertex;
  private Vertex toVertex;
  private Double weight;
 
  public Edge() {
  }
 
  public Edge(Vertex fromVertex, Vertex toVertex, Double weight) {
    this.fromVertex = fromVertex;
    this.toVertex = toVertex;
    this.weight = weight;
  }
  
  @Override
  public String toString() {
      return fromVertex.getLabel()+" to "+
             toVertex.getLabel()+" with weight "+ 
             getWeight();
  }
 
  public Vertex getFromVertex() {
    return fromVertex;
  }
 
  public void setFromVertex(Vertex fromVertex) {
    this.fromVertex = fromVertex;
  }
 
  public Vertex getToVertex() {
    return toVertex;
  }
 
  public void setToVertex(Vertex toVertex) {
    this.toVertex = toVertex;
  }
 
  public Double getWeight() {
    return weight;
  }
 
  public void setWeight(Double weight) {
    this.weight = weight;
  }
}
<p class="indent">

Vertex.java

ublic class Vertex implements Comparable<Vertex> {
  private String label;
 
  public Vertex(String label) {
    this.label = label.toUpperCase();
  }
   
  @Override
  public int compareTo(Vertex o) {
    return (this.getLabel().compareTo(o.getLabel()));
  }
 
  public String getLabel() {
    return label;
  }
 
  public void setLabel(String label) {
    this.label = label;
  }
}
<p class="indent">




相關文章