我以两种不同的方式为我的课程建模:一个使用?而另一个使用T扩展了SomeClass。我想知道哪种方法是正确的方法。 基本上我有一个对象,我想将它保留在我的数据存储区中。从客户端我刚收到一个客户,我向该对象添加一些metaDataInfo,然后选择该对象的Id /密钥,然后使用密钥和对象将其保留。我想确保我持久化的对象有metaInfo而不仅仅是任何对象。
使用T的Option1扩展了SomeClass:
public class Client {
public static void main(String[] args) {
Customer customer = new Customer();
Persister.save(customer);
}
static class Persister {
static void save(Customer customer) {
EntityWithMetaDataImpl<Customer> entityWithMetaData = new EntityWithMetaDataImpl<>("metadata", customer);
String key = "key";
PersistentEntity<EntityWithMetaDataImpl<Customer>> impl = new PersistentEntity<>(key, entityWithMetaData);
ActualPersister.save(impl);
}
}
static class ActualPersister {
static <T extends EntityWithMetaData> void save(PersistentEntity<T> entity) {
// save record with entity.getObjectKey() and
// entity.getActualObject();
}
}
}
public class Customer {
String name;
public String getName() { return name;}
public void setName(String name) { this.name = name; }
}
public interface EntityWithMetaData {
public String getMetaData();
}
public class EntityWithMetaDataImpl<T> implements EntityWithMetaData {
private T actualObject;
private String metaData;
EntityWithMetaDataImpl(String metaData, T actualObject) {
this.metaData = metaData;
this.actualObject = actualObject;
}
public T getActualObject() {
return actualObject;
}
@Override
public String getMetaData() {
return metaData;
}
}
public class PersistentEntity<T extends EntityWithMetaData> {
String key;
T actualObject;
PersistentEntity(String key, T entity){
this.key = key;
this.actualObject = entity;
}
public String getObjectKey() { return key;}
public T getActualObject() { return actualObject; }
}
Option2使用?:
public class Client {
public static void main(String[] args) {
Customer customer = new Customer();
Persister.save(customer);
}
static class Persister {
static void save(Customer customer) {
EntityWithMetaData<Customer> entityWithMetaData = new EntityWithMetaData<>("metadata", customer);
String key = "key";
PersistentEntity impl = new PersistentEntity(key, entityWithMetaData);
ActualPersister.save(impl);
}
}
static class ActualPersister {
static void save(PersistentEntity persisterEntity) {
// save record with persisterEntity.getObjectKey() and
// persisterEntity.getActualObject();
}
}
}
public class EntityWithMetaData<T>{
private T actualObject;
private String metaData;
EntityWithMetaData(String metaData, T actualObject) {
this.metaData = metaData;
this.actualObject = actualObject;
}
public T getActualObject() {
return actualObject;
}
public String getMetaData() {
return metaData;
}
}
public class PersistentEntity {
String key;
EntityWithMetaData<?> actualObject;
PersistentEntity(String key, EntityWithMetaData<?> entity){
this.key = key;
this.actualObject = entity;
}
public String getObjectKey() {
return key;
}
public EntityWithMetaData<?> getActualObject() {
return actualObject;
}
}