java - 具有行数据网关的注册表模式

标签 java design-patterns

我正在阅读 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);
    }
}

上面的代码调用了registry类,但是我不确定Registry类的好处是什么。我已经阅读了有关注册表类的章节,但我仍然不清楚。我知道它们是静态方法。

最佳答案

在这种情况下,注册表的作用就像一个缓存(或者您很快就会看到或可能已经看到的 IdentityMap),如果您的应用程序已经拥有对 Person 对象的引用,它将不会从数据库中获取它。

摘自书中

When you want to find an object you usually start with another object that has an association to it, and use the association to navigate to it. Thus, if you want to find all the orders for a customer, you start with the customer object and use a method on it to get the orders. However, in some cases you won't have an appropriate object to start with.

Registry 模式基本上是对象引用的持有者,因此您不必遍历复杂的对象依赖关系来获取链中的最后一个对象。示例(您在实践中永远不会看到):

class Book {
    public Author author;
}

class Author {
    public City city;
}

class City {
    public String name;
}

您不想通过 Book -> Author 来获取 City 对象。

您通常使用Registry来保留对全局对象的引用,这就是Fowler建议使用静态方法的原因,但正如您在第409页上所读到的,您应该很少使用此模式“作为最后的手段”

设计不当注册表示例

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);
    }
}

每当您创建某个类的实例时,您都会在注册表中注册它,以便整个应用程序都可以访问它(这可能会导致比它解决的问题更多的问题)。

关于java - 具有行数据网关的注册表模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16067680/

相关文章:

java - 泛型方法上的多个通配符使 Java 编译器(和我!)非常困惑

java - Android java完成后停止动画

java - 工厂模式: Accessing child methods

c# - 有生产工厂的工厂可以吗?

ios - UICollectionView 和 MVVM

Java解析args中的JSON

java - 为什么 java.util.Stack 不使用 LinkedList 的复合模式,而是使用 Vektor?

java - 使用比较器进行集合排序,给出 IllegalArgumentException

java - OO 设计问题接口(interface)和类

javascript - 采用 JSON 并将其分配给各种属性/innerHTML 的好模式是什么?