为什么喜欢构图而不是继承呢?每种方法都有哪些权衡取舍?什么时候应该选择继承而不是作文?
可能重复:
首选组合而不是继承?
java中的继承和委托有什么区别?
如何在我的项目中使用以下示例?请告诉我代表团.我知道继承,但对授权知之甚少.所以,请给出正确的理由.我为什么要用这个?
package com.m;
class RealPrinter { // the "delegate"
void print() {
System.out.println("something");
}
}
class Printer { // the "delegator"
RealPrinter p = new RealPrinter(); // create the delegate
void print() {
p.print(); // delegation
}
}
public class Tester {
// to the outside world it looks like Printer actually prints.
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
}
}
Run Code Online (Sandbox Code Playgroud)