委托在这里如何应用?

问题描述

有人可以解释委派模式如何应用于以下代码吗? 我知道它允许对象组合实现与继承相同的代码重用,但是我很难在代码示例中理解它。

    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`

解决方法

由于Stack类实例化了ArrayList类(list)中的变量,因此当您在list上调用方法时,您将委托给{{1} }类。

委派意味着您将另一个类的对象用作 实例变量,并将消息转发到实例。 https://www.geeksforgeeks.org/delegation-vs-inheritance-java/

您正在使用ArrayList类中的ArrayList类中的方法。当其他类使用Stack类时,他们会认为这些操作是由Stack类处理的。局外人不知道Stack类实际上是在将指令传递给Stack类。