Java - 从方法返回多个对象类型的最佳方法

Cat*_*ish 8 java inheritance containment

在我的DAO我有一个方法,我建立2个不同的对象,我想要返回这两个对象,但我不知道最好的方法是做什么.我已经看过使用? extends myObject,创建另一个类,它包含我想要返回的两个对象,并且只是使用List<Object>.

长话短说我为什么需要这些类似的对象是在屏幕上显示1而另一个用于primefaces dataexporter,据我所知,它不处理对象中的列表.

班级人员

public class Person() {
  firstName = null;
  lastName = null;
  List<Programs> programs = new ArrayList<Programs>();

  // Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

类DataExporterPerson

public class DataExporterPerson() {
  firstName = null;
  lastName = null;
  String program = null;

  // Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

DAO方法:

public List<SOMETHING> getPeople() {
  // query db for people

  // build both objects

  return ?????
}
Run Code Online (Sandbox Code Playgroud)

现在我明白我可以很容易地创建另一个对象,如下面的那个,但这似乎是一种低效的做事方式,因为我基本上创建一个对象只是为了从1方法返回.

public class PersonTransporter() {
  Person person = null;
  DataExporterPerson = null;
}
Run Code Online (Sandbox Code Playgroud)

处理这种情况的最佳方法是什么?

编辑

我试图在1方法中返回2个对象的原因是因为这是一个DAO方法,它查询数据库并根据查询中的数据构建2个对象.我不想将其分解为2种方法,因为如果我不需要,我不想查询数据库两次.

Pet*_* B. 8

您可以通过继承或包含来处理此问题.

你可以拥有PersonDataExporterPerson扩展类似的东西AbstractPerson.但是,由于您尚未这样做,因此继承可能是不合适的.

我认为有效的C++讨论了遏制如何比继承更好.IIRC的理由是,遏制比继承更松散耦合.

在这里你将有一个包含Person和的对象 DataExporterPerson.您的方法将为此联合类型对象填充其中一个,并通过查看哪个为null,您将知道您实际拥有哪个.

public class DBPersonUnion {
  private Person person = null;
  private DataExporterPerson dataExporterPerson = null;

  //getters and setters.
}
Run Code Online (Sandbox Code Playgroud)


Dam*_*ash 5

如果您的方法需要返回两种不同的类型,则暗示您的体系结构或方法逻辑存在问题.

你可以做什么 ?

  • 创建一个逻辑上连接元素的类,
  • 介绍两个类都将实现的通用接口,
  • 实现两个方法,用对象返回,第二个使用参数并返回第二个对象.

最后一点的例子

 class Foo {
    String f;
 } 

 class Bar {
   String b;
 }
Run Code Online (Sandbox Code Playgroud)

那么问题如何返回对象Foo和Bar?

 public Object theProblemMethod() {

      Foo a = new Foo();
          a.foo = "Test";

      Bar b = new Bar();
          b.bar = a.foo;   //The logic where class Foo meet class Bar.

    return ???

 }
Run Code Online (Sandbox Code Playgroud)

有效的实施

   public Foo createFoo(){ 
      Foo a = new Foo();
          a.foo = "Test";
      return a;
   } 

   public Bar createBar(Foo f) {

      Bar b = new Bar();
          b.bar = f.foo; 
      reutrn b;
   }
Run Code Online (Sandbox Code Playgroud)

用法

   public void action()  {

           //theProblemMethod(); //This we can not do

          Foo a = createFoo();
          Bar b = createBar(a);
  }
Run Code Online (Sandbox Code Playgroud)