【问题标题】:How can I use a 'next generation' java data object style together with interfaces?如何将“下一代”Java 数据对象样式与接口一起使用?
【发布时间】:2012-04-28 19:52:52
【问题描述】:

我的大部分不可变数据对象都采用以下风格编写,有时被描述为'next generation' 或“功能性”:

public class Point {
   public final int x;
   public final int y;

   public Point(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

我想对接口指定的数据对象使用相同的样式:

public interface Point {
   public final int x;
   public final int y;
}

public class MyPoint {
   public MyPoint(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

public class Origin {
   public Origin() {
      this.x = 0;
      this.y = 0;
   }
}

但是java不允许这样做,这会在接口代码和实现中产生错误。

我可以把我的代码改成

public interface Point {
   public int x();
   public int y();
}

public class MyPoint {
   private int mx, my;
   pulic MyPoint(int x, int y) {
      mx = x;
      my = y;
   }
   public int x() {return mx;}
   public int y() {return my;}
}

public class Origin {
   public int x() {return 0;}
   public int y() {return 0;}
}

但它是更多的代码,我不认为它在 API 中给人几乎相同的简单感觉。

你能找到摆脱困境的方法吗?还是您个人使用第三种甚至更简单的样式?

(我对可变/不可变、getterSetter/new-style 或私有/公共字段的讨论并不感兴趣。)

【问题讨论】:

  • 是我遗漏了什么,还是“下一代”只是“不可变类型”?
  • 是的,可以这么说。

标签: java interface immutability field encapsulation


【解决方案1】:

我宁愿改用继承或委托

public class Point {
 public final int x;
 public final int y;

 public Point(int x, int y) {
   this.x = x;
   this.y = y;
 }
}

继承

public class MyPoint extends Point {
   public MyPoint (int x, int y) {
     super (x, y);
   }
   ....
}

public class Origin extends Point {
   public Origin () {
     super (0, 0);
   }
}

【讨论】:

  • 好的,但是可能有些字段不应该由用户设置。例如。 Tree 中的字段 height。我想那么您会将“主类”中的构造函数设置为受保护?
  • 我并没有真正理解你。您在哪个对象中有附加字段?
  • 假设我们有 Node 和公共最终字段 valueheight。我们还有两个子类BranchLeaf。在Branch 的构造函数中,height 是从它的子元素中计算出来的,而在Leaf 的构造函数中,它被设置为0。我们显然不希望用户能够调用new Node(int value, int height)。充其量是不应该知道的。
猜你喜欢
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 2018-02-07
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多