如何在这里应用委托?

huangapple go评论90阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月18日 05:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63458592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定