[英]Creating a generic class for single obj, list<obj> and has-a objs?
With the following class: 使用以下课程:
public class Foobar<T> implements Serializable {
private Boolean isTrue;
private String randomMessage;
private T data;
}
How when constructing an object of Foobar here can I decide that my data variable might be either the following: 在这里构造Foobar的对象时,如何确定我的数据变量可能是以下之一:
has-a
objects has-a
对象 How can this class support something like that? 此类如何支持这样的事情? where I can throw those different scenarios at it to handle it robustly?
在哪里可以扔那些不同的场景来稳健地处理它? Is this an attempt to be too abstract, should I just create multiple classes?
这是不是太抽象了?我应该只创建多个类吗?
This is a candidate for inheritance. 这是继承的候选人。
Create an abstract class: 创建一个抽象类:
public abstract class Foobar<T> implements Serializable { ...
Then create three different classes for each type of content: 然后为每种类型的内容创建三个不同的类:
public class FoobarSingle<T> extends Foobar<T> {
T data;
...
public class FoobarList<T> extends Foobar<T> {
List<T> data;
...
public class FoobarComplex<T> extends Foobar<T> {
T data;
Object anotherField;
...
Another option is to make a single class Foobar<T>
and a abstract container class for the data it holds: 另一个选择是使单个类
Foobar<T>
和一个抽象容器类为其保存的数据:
public class FoobarSingle<T> extends Foobar<T> {
FoobarContainer<T> data;
...
FoobarContainer
may then be subclassed to hold different kinds of data. 然后可以将
FoobarContainer
子类化以保存不同种类的数据。
Either way, you must be prepared to handle different kinds of data depending on the actual class, which you can use instanceof
operator to. 无论哪种方式,您都必须准备根据实际的类来处理不同类型的数据,可以使用
instanceof
运算符进行处理。
There is the option of having private fields in a single Foobar
class for different types of data and then access them by overloaded methods: 可以选择在单个
Foobar
类中具有私有字段来存储不同类型的数据,然后通过重载方法访问它们:
setData(T car) { ... }
setData(List<T> car) { ... }
setData(T car, Object otherProperty) { ... }
But this approach is prone to errors, since you must yourself manage situations where one type of content is written and other type is attempted to read. 但是这种方法容易出错,因为您必须自己管理写一种类型的内容而尝试读另一种类型的内容的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.