伙计们正在寻找组合和继承之间的区别,然后我在某个地方找到了这篇文章。
根据post组合在代码重用方面优于继承。
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return fruit.peel();
}
}
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
更改后端类
class Peel {
private int peelCount;
public Peel(int peelCount) {
this.peelCount = peelCount;
}
public int getPeelCount() {
return peelCount;
}
//...
}
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public Peel peel() {
System.out.println("Peeling is appealing.");
return new Peel(1);
}
}
// Apple 必须更改以适应 // 对 Fruit 的更改
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
Peel peel = fruit.peel();
return peel.getPeelCount();
}
}
// Example2 的旧实现 // 仍然可以正常工作。
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
这是我没有根据帖子所说的“如果后端类的接口发生变化,前端类的实现也会发生变化,但它的接口不会发生变化”。
这里的接口是什么实现是什么?
这只是我的假设,如果我错了,请告诉我??(也许一切都错了)。
后端类是接口,因为前端类依赖于它吗?
前端类的实现是前端类内部的实现代码吗?前端
类
是否也是一个接口,因为 Example 中的代码依赖于它?
它们是否因为更改后端接口没有更改前端接口而耦合得很糟糕?所以依赖前端接口的代码还是可以的。
如果我使用继承而不是子类在超类中紧密耦合?因为对超类的更改也会更改为子类,因此依赖于子类的代码可能无法正常工作。
Wny 继承是弱封装。