我有一个值对象(Test2
),它将保存许多可选的数据结构(实现PropertySet
)。我不能将它们全部组合到Test2
中,因为会有很多变体,实现所有排列会导致类的扩散。我想出了以下解决方案:
public class Test2
{
static interface PropertySet
{
}
static class LocationInfo implements PropertySet
{
String lat;
String lng;
public LocationInfo(String lat, String lng)
{
this.lat = lat;
this.lng = lng;
}
}
private Map<Class<? extends PropertySet>, PropertySet> propertySets = new HashMap<>();
@SuppressWarnings("unchecked")
public <T extends PropertySet> T fetchPropertySet(Class<? extends T> propertySetType)
{
T result = (T) propertySets.get(propertySetType);
return result;
}
public LocationInfo getLocationInfo()
{
return this.<LocationInfo> fetchPropertySet(LocationInfo.class);
}
public static void main(String[] args)
{
Test2 test = new Test2();
test.propertySets.put(LocationInfo.class, new LocationInfo("1", "1"));
LocationInfo locationInfo = test.<LocationInfo> fetchPropertySet(LocationInfo.class);
System.out.println(locationInfo.lat + ", " + locationInfo.lng);
LocationInfo locationInfo2 = test.getLocationInfo();
System.out.println(locationInfo2.lat + ", " + locationInfo2.lng);
}
}
我的问题是,这种解决方案是否被认为是这种问题的良好实践?
请注意,我不能使用外部库,如Guava,但使用了Java 8。
type.cast(…)
如何使@SuppressWarnings("unchecked")
变得不必要。 - Holger