How to implement a delegate template (e.g. in objective-c) in java

I looked at an example where the explanation of the explanation template for java. I did not find much use for this (sorry ignorance), because I feel that he lacks flexibility in objective-c. Is there a way to dynamically set a delegate object, how can this be done in objective-c. Isn't that the whole delegation’s business? My knowledge of java is very preliminary, so please explain a little more.

+5
source share
2 answers

I think there are many ways to implement the delegation pattern in Java, but probably not, which seems to be inline.

. - , , , .

, , , . - - , AspectJ.

( ), :

class Person {
  @Delegate Animal animal;
  ...
}

, @Delegate class (, Person).

groovy JVM-, , :

, , Groovy. ( , Person, ... !)

+8

Java. , . , , , -. , , , , IndexOutOfBounds ClassCastException .

public interface DelegatedFunction<T> {

T call(Object... args);

}

public class DoesSomeDelegatedTask {

  private List<DelegatedFunction<String>> delegatedFunctions = new ArrayList<>(1);

  public void addFunction(DelegatedFunction<String> function) {
    delegatedFunctions.add(function);
  }

  public void execute() {
    for (DelegatedFunction<String> function: delegatedFunctions) {
      System.out.println(function(something, someotherthing, whatever));
    }
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    DoesSomeDelegateTask doer = new DoesSomeDelegatedTask();
    doer.addFunction(new DelegatedFunction<String> () {
      @Override
      public String call(Object... args) {
        return ((SomeThings) args[0]).whatever((SomeOtherThing) args[1]//you get the idea
      }
    }
    doer.execute();
  }
}
+2

All Articles