【问题标题】:Design patterns and conventions for object conversion [closed]对象转换的设计模式和约定[关闭]
【发布时间】:2016-03-20 01:23:27
【问题描述】:

在对象转换方面,以下两种方法的首选方法是什么?

使用 asX() 方法进行对象转换

public class Foo {
  int foo;
  public Bar asBar() {
    return new Bar(foo);
  }
}

class Bar {
  int bar;
  public Bar(int bar) {
    this.bar = bar;
  }
}

使用构造函数进行对象转换

public class Foo {
  int foo;
}

class Bar {
  int bar;
  public Bar(int bar) {
    this.bar = bar;
  }

  public Bar(Foo foo) {
    this.bar = foo.foo;
  }

}

与另一种方法相比,我不确定这两种方法的优点(在可维护性、可扩展性等方面)。既定标准是什么?

我接受 Paul Boddington 在 cmets 中指出的问题相当广泛,但希望在此问题结束之前进行一些有用的讨论。

【问题讨论】:

  • 您应该将转换的责任放在不同的对象中。如果您还想将Foo 转换为Bar 以外的其他类型怎么办?你最终会在你的类中得到一堆转换方法。不仅如此,如果你以后决定添加其他转换方法,就会违反O/C原则。
  • 除了目前建议的 3 种方法外,您还可以使用 static 方法进行转换。我觉得这个问题实在是太笼统了,没有正确答案。
  • @VinceEmigh 通过引入一个仅用于对象之间转换的类不会使命名空间变得混乱。对我来说,将此类转换方法放在正在转换为/从的任何一个类中是有意义的。
  • 一点也不。这就像说FileReaderFileWriter 使命名空间混乱,它们的行为应该直接放在File 类中。它遵守单一职责原则。话又说回来,这真的完全取决于您的应用程序的要求。
  • @SamTebbs33,看看这个 SE 问题:stackoverflow.com/questions/34280716/…

标签: java coding-style standards conventions


【解决方案1】:

我见过用的很多而且我个人喜欢的是很多JDK本身使用的样式,它涉及到目标类中的静态工厂方法。最终目标是让代码易于阅读。

例如:

Integer.fromString("42")

从 OP 中的示例中借出:

public class Foo {
  int foo;
}

class Bar {
  int bar;

  public static Bar fromFoo(Foo foo) {
    return new Bar(foo.foo);
  }

  public Bar(int bar) {
    this.bar = bar;
  }

}

这样,某人可以从Foo 创建Bar,并且这样做时代码读取良好:

Bar bar = Bar.fromFoo(foo);

它读起来几乎像英语,而不是 COBOL!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2011-05-02
    相关资源
    最近更新 更多