假设我有以下类型的数据:
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);
}
}
好的,我已经知道继承是 3v1l,所以让我们尝试组合:
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 原则和所有最佳实践的最佳方法是什么。创建除了扩展已经存在的集合之外什么都不做的类似乎是不必要地增加实体,但会使我的代码更清晰(特别是当有下一个级别时 - 例如按月划分的 AllConnections 地图等)。有什么方向吗?