class Customer {
String id; // unique
OtherCustData someOtherData;
}
class Service {
String url; // unique
OtherServiceData someOtherData;
}
class LastConnection {
Date date;
OtherConnData someOtherData; // like request or response
}
现在我需要记住每个客户端连接到每个服务的时间。
我会建立以下结构:
Map<Customer, Map<Service, LastConnection>> lastConnections;
或者,为了能够通过ID进行搜索而不必编写所有的equal()和hashCode():
Map<String, Map<String, LastConnection>> lastConnections;
现在我可以通过以下方式访问LastConnection数据:
LastConnection connection = lastConnections.get(custId).get(srvUrl);
所有这些看起来很丑,尤其是我必须将它作为参数传递给许多期望LastConnections映射的映射的方法,因此我考虑创建自己的类,它应该看起来像这样:
class CustomerConnections extends HashMap<String, LastConnection> {
}
class AllConnections extends HashMap<String, CustomerConnections> {
public LastConnection get(String custId, String srvUrl) {
return get(custId).get(srvUrl);
}
}
好的,我已经了解到继承是有害的,那么让我们尝试组合:
class CustomerConnections {
Map<String, LastConnection> customerConnections;
LastConnection get(String srvUrl) {
return customerConnections.get(srvUrl);
}
... // all other needed operations;
}
class AllConnections {
Map<String, CustomerConnections> allConnections;
public LastConnection get(String custId, String srvUrl) {
return get(custId).get(srvUrl);
}
public CustomerConnection get(String custId) {
return allConnections.get(custId);
}
... // all other needed operations;
}
问题在于我不确定在尊重SOLID原则和所有最佳实践方面,哪种方法是最好的。创建除了扩展已经存在的集合之外什么都不做的类似乎是在增加不必要的实体,但会使我的代码更清晰(特别是当有下一级 - 比如按月份分类的所有连接的映射)。有任何建议吗?