英文:
How is delegation applied here?
问题
以下是翻译好的部分:
有人能否解释一下委托模式如何应用到以下代码中?
我理解它允许对象组合实现与继承相同的代码重用,但我在使用代码示例方面有困难。
// Java程序演示委托
class RealPrinter {
// "委托者"
void print()
{
System.out.println("委托者");
}
}
class Printer {
// "代理者"
RealPrinter p = new RealPrinter();
// 创建委托
void print()
{
p.print(); // 委托
}
}
public class Tester {
// 对外部世界来说,看起来好像是Printer实际上在打印。
public static void main(String[] args)
{
Printer printer = new Printer();
printer.print();
}
}
英文:
Would someone be able to explain how the delegation pattern is applied to the following code?
I understand that it allows object composition to achieve the same code reuse as inheritance, but I've trouble understanding it with the code example.
brightness_4
// Java program to illustrate
// delegation
class RealPrinter {
// the "delegate"
void print()
{
System.out.println("The Delegate");
}
}
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();
}
} `enter code here`
答案1
得分: 1
由于Stack
类从ArrayList
类实例化一个变量(list
),当您在list
上调用方法时,您正在委托给ArrayList
类。
> 委托意味着您将另一个类的对象用作实例变量,并将消息转发给实例。
https://www.geeksforgeeks.org/delegation-vs-inheritance-java/
您的Stack
类正在使用ArrayList
类的方法。当其他类使用Stack
类时,它们会认为操作是由Stack
类处理的。外部人员不知道实际上Stack
类正在将指令传递给ArrayList
类。
英文:
Since the Stack
class instantiates a variable from the ArrayList
class (list
), when you call methods on list
you're delegating to the ArrayList
class.
> Delegation means that you use an object of another class as an
> instance variable, and forward messages to the instance.
https://www.geeksforgeeks.org/delegation-vs-inheritance-java/
You are using methods from the ArrayList
class for your Stack
class. When other classes use the Stack
class, they will think that the operations are handled by the Stack
class. Outsiders do not know that the Stack
class is actually passing the instruction on to the ArrayList
class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论