Java中的委托(delegate)是什么?谁能给我一个适当的例子?

最佳答案

那是代表团-就像在现实世界中一样:

public interface Worker() {
  public Result work();
}

public class Secretary() implements Worker {

   public Result work() {
     Result myResult = new Result();
     return myResult;
   }
}

public class Boss() implements Worker {

   private Secretary secretary;

   public Result work() {
     if (secretary == null) {
        // no secretary - nothing get's done
        return null;
     }
     return secretary.work();
   }

   public void setSecretary(Secretary secretary) {
       this.secretary = secretary;
   }
}

(添加了工作程序界面以更接近委托(delegate)人模式)

09-05 09:27