2013-04-17 28 views
1

我正在閱讀Martin Fowlers的一本書,即企業應用程序模式:ftp://ftp.heanet.ie/mirrors/sourceforge/w/we/webtune/Patterns%20of%20Enterprise%20Application%20Architecture.pdf。我已經涉及了行數據網關模式,特別是註冊表模式。下面是這本書的第149頁的代碼片段:使用行數據網關的註冊表模式

public static Person find(Long id) { 
    Person result = (Person) Registry.getPerson(id); 
    if (result != null) 
     return result; 
    PreparedStatement findStatement = null; 
    ResultSet rs = null; 
    try { 
     findStatement = DB.prepare(findStatementString); 
     findStatement.setLong(1, id.longValue()); 
     rs = findStatement.executeQuery(); 
     rs.next(); 
     result = load(rs); 
     return result; 
    } catch (SQLException e) { 
     throw new ApplicationException(e); 
    } finally { 
     DB.cleanUp(findStatement, rs); 
    } 
} 

上面的代碼調用登記類,但我不知道註冊表類的好處是什麼。我已閱讀關於註冊表課程的章節,但我仍不清楚。我明白他們是靜態方法。

回答

1

在這種情況下,註冊表是像個緩存(或IdentityMap你很快就會看到或有可能的話),在那裏,如果你的應用程序已經有到Person對象的引用,也不會去得到它來自數據庫。

從書

當你想找到一個對象,你通常與其他對象 有一個協會,它啓動,並使用聯想導航到 它。因此,如果您想查找客戶的所有訂單,則可以使用客戶對象啓動 ,並使用其上的方法獲取訂單。 但是,在某些情況下,您將沒有適當的對象來啓動 。

Registry模式基本上是對象引用的持有者,因此您不必遍歷複雜對象依賴關係以獲取鏈中的最後一個對象。示例(你永遠不會在實踐中看到):

class Book { 
    public Author author; 
} 

class Author { 
    public City city; 
} 

class City { 
    public String name; 
} 

你不想要經過Book -> Author得到City對象。

您使用Registry通常保持引用全局對象這就是爲什麼福勒建議使用static方法,但你可以在閱讀page 409,你應該很少使用這種模式"as a last resort"

不佳做作註冊例如

class CityRegistry { 
    private static Map<String, City> references = new HashMap<>(); 
    public static void registerCity(String id, City reference) { 
     references.put(id, reference); 
    } 

    public static City getCity(String id) { 
     return references.get(id); 
    } 
} 

每當你需要創建一些類的實例,你將在Registry註冊它使整個應用程序可以訪問它(這可能會導致比更多的問題它解決了)。

+0

爲什麼你需要通過Book - > Author來獲取City對象?你能提供一個註冊表的例子嗎?感謝+1。 – w0051977

+0

@ w0051977你不會這樣做,但是在一個更復雜的例子中,你可能不得不爲了在對象層次結構中找到一些實例。 –

+0

謝謝。因此,不要在所有地方傳遞id,而是將它傳遞到註冊表並將該對象保存在註冊表中。 – w0051977