承接前兩篇,本文深入探討 Rational XDE 中模式機制的進階主題:代碼模板、模式腳本、值源與值集、約束元素、Callouts 以及模式組合。這些特性讓模式不僅能描述靜態結構,更能生成動態代碼、處理複雜邏輯並組合成大尺度解決方案。
設計模式多關注結構(類、關係),方法內部邏輯難以標準化。XDE 引入代碼模板,支援參數化生成方法體代碼,類似 JSP/ASP 語法:
<% ... %> 包裹的 JavaScript 邏輯,可操作模型元素 API。<%= var %> 輸出變量值。Strings:簡單字串,展開時直接替換。Model Elements:模型元素(類、方法等),可透過 API 遍歷屬性、方法實現複雜定制。<%
function debugStatements(myClass) {
var attrs = myClass.GetAttributeCollection();
var coll = Interfaces.queryInterface(attrs, "com.rational.rms.IRMSElementCollection");
var count = coll.getCount();
for (var i=1; i<=count; i++) {
var attr = coll.GetElementAt(i);
var name = attr.getName();
%>
System.out.println( "<%=name%>" );
<%
}
}
var op = Interfaces.queryInterface(thisElement, "com.rational.uml70.IUMLOperation");
var cls = Interfaces.queryInterface(op.GetContainer(), "com.rational.uml70.IUMLClass");
debugStatements(cls);
%>
套用此模板的方法,執行前會自動印出所有屬性值,極利於除錯。
模板參數可綁定模式的模板參數。例如:
<%=codetp%> a<%=codetp%>Object = new <%=codetp%>();
若 codetp 綁定 ClassTP,展開後變為:
ClassTP aClassTPObject = new ClassTP();
腳本不限於代碼模板,可用於類名、屬性名、文檔註釋、關聯端點等任意字串位置。語法:<%= scriptlet %>。
<%= tp1 %> → 實際類名。Name Length: <%= tp1.getName().length() %>。function show_props(obj, name) {
for (var p in obj) {
EAEventData.AddOutputMessage(name + "." + p + " = " + obj[p]);
}
}
show_props(tp1, "tp1"); // 在輸出視窗列出所有可用屬性/方法
模板參數的值源決定輸入方式:
| 類型 | 說明 |
|---|---|
| User | 預設。使用者從現有模型選擇元素綁定。 |
| Generated | 自動建立新元素,使用者僅提供名稱。 |
| Collection | 從宿主元素衍生集合(如某類的所有 public 屬性)作為參數值。 |