gpt4 book ai didi

java - 如何在java中包装类并保存接口(interface)?

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:41 25 4
gpt4 key购买 nike

我有这样的类(class):

MyClass extends MyAbstractClass implement myInterface1, myInterface2,...

我需要创建带有附加字段的新类:

MyType1 field1;
MyType2 field2;
.......

似乎正确创建将包装 MyClass 的新类,如下所示:

MyWrapClass {
MyClass myClass=new MyClass(...);
MyType1 field1;
MyType2 field2;
.....

但是 MyWrapClass 用作 myInterface1 或 myInterface2 类型!

所以问题是:我是否应该在 MyWrapClass 中声明接口(interface) myInterface1、myInterface2 所需的所有方法?或者以另一种方式存在?谢谢。

最佳答案

基本上,有两种方法。第一个是扩展基类:

public class MySubClass extends MyClass {
private MyType1 field1;
private MyType2 field2;
....

第二种选择是使用组合:

public class MySubClass implements myInterface1, myInterface2 {
private MyClass delegate;
private MyType1 field1;
private MyType2 field2;

// for all methods in myInterface1, myInterface2
public SomeType method1() {
return delegate.method1();
}
...
}

第二个选项被许多 Java 专家推荐:

Josh Bloch 的书 Effective Java 2nd Edition

  • 第 16 条:组合优先于继承
  • 第 17 项:设计和继承文件或禁止继承

好的面向对象设计并不是要自由地扩展现有的类。你的第一个 本能应该是作曲。

另见 http://en.wikipedia.org/wiki/Composition_over_inheritance

Composition over inheritance can simplify the initial design of Business Domain classes and provide a more stable business domain in the long term. Its advantage over inheritance is a more thorough isolation of interests than can be described by a hierarchy of descendant classes. Additionally, inheritance models are often contrived during the definition of business domain classes in order to make sense of the information in the problem domain and do not necessarily reflect the true relationship of various system objects.

P.S.:一些现代 IDE 支持自动生成组合代码

关于java - 如何在java中包装类并保存接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10014680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com