维基百科文章 (https://en.wikipedia.org/wiki/Delegation_(programming)) 正在讨论一个名为“委托”的功能,这是我没有经历过的。
引用您引用的维基百科文章中的#1:
"调用 b.foo() 将导致 b.bar 被打印,因为 this 在 a 的上下文中引用原始接收器对象 b。"
他们基本上覆盖了 A 类中的“this”,因此它恰好指向 B 类的一个实例。我怀疑这种覆盖是临时的,并且可能会从对 A 类方法的调用变为调用。如果 A 类的给定实例充当 B、C 和 D 类的“代表”,所有这些都具有不同的“bar()”实现,那么祝你好运。
如果“this”在运行时是任意的 B 类或(C 类 ... Z 类),我不想成为负责编写 A 类的程序员;感觉就像一个研究课题,对论文很有帮助,但对日常工作编程可能没有太大帮助。我有兴趣阅读 stackexchange 人群可以提供的任何示例,他们认为这种行为有帮助。
引用您引用的维基百科文章中的#2:
“一般的编程语言不支持这种不寻常的委托形式作为语言概念,但也有一些例外[需要引用]”
我同意 [需要引用],我很想知道任何实际支持这一点的语言。
示例 Java 输出
请注意,Java 并不像 Wikipedia 文章所描述的那样工作。
在源代码中使用“委托”一词可能毫无意义,因为它具有误导性,至少在维基百科文章概念的意义上是这样。但我将其保留是为了更容易将维基百科示例“代码”与以下内容进行比较。
$ java B
> B(), adding delegateA@2a139a55
< B()
----- a.foo() ---
> A.foo(), calling this.bar()
A.bar(): hello from a.bar
< A.foo(), back from this.bar()
----- a.bar() ---
A.bar(): hello from a.bar
----- b.foo() ---
> B.foo(), calling a.foo()
> A.foo(), calling this.bar()
A.bar(): hello from a.bar
< A.foo(), back from this.bar()
< B.foo(), back from a.foo()
----- b.bar() ---
B.bar(): hello from b.bar
$
现在...作为一个思想实验,如果 java 实现了那种“委托”,输出的最后一部分看起来(我认为)更像这样:
//This isn't actual output from java at all,
//I just edited this trying to make it look like
//what I think the wikipedia-style "delegation" would do.
----- b.foo() ---
> B.foo(), calling a.foo()
> A.foo(), calling this.bar()
B.bar(): hello from b.bar // Big difference here vs. actual java output above.
< A.foo(), back from this.bar()
< B.foo(), back from a.foo()
----- b.bar() ---
B.bar(): hello from b.bar
$
A 类
class A {
void foo() {
System.out.println("> A.foo(), calling this.bar()");
this.bar();
System.out.println("< A.foo(), back from this.bar()");
}
void bar() {
System.out.println("A.bar(): hello from a.bar");
}
}
B 类
class B {
// private delegate A a; // delegation link
// above line doesn't compile in Java, "delegate" not a key word.
private A a; // delegation link, without "delegate" key word.
public B(A a) {
System.out.println("> B(), adding delegate"+a+"");
this.a = a;
System.out.println("< B()" );
}
void foo() {
System.out.println("> B.foo(), calling a.foo()");
a.foo(); // call foo() on the a-instance
System.out.println("< B.foo(), back from a.foo()");
}
void bar() {
System.out.println("B.bar(): hello from b.bar");
}
public static void main( String args[] ) {
A a = new A();
B b = new B(a);
System.out.println("----- a.foo() ---");
a.foo();
System.out.println("----- a.bar() ---");
a.bar();
System.out.println("----- b.foo() ---");
b.foo();
System.out.println("----- b.bar() ---");
b.bar();
}
}