Allows multiple objects implementing methods with different name or type (instance or static) but compatible signatures to be used interchangeably.


Delegates is conceptually similar to the notion of function pointers. Java does not provide Delegates natively therefore the need for this implementation, see A Java Programmer Looks at C# Delegates article. See also Sun's critic of Delegates.

The introduction of the Delegates implementation in PerfectJPattern is more a means to componentize some of the Design Patterns rather than offering Delegates as ultimate design building block for end applications. The Delegates feature is nevertheless included in PerfectJPattern public API for cases where would be needed e.g. it effectively abstracts from low-level Java Reflection machinery.

Notes about PerfectJPattern's Delegates implementation:

  • A function pointer is represented as a Java interface that exposes one single method
  • There is no strongly typed way to identify via Reflection a Java Method so far. When building the delegate, the target method is referred by its String name. The tentative to build a delegate over a method that no longer exists or its signature does not match, will result in a predefined Runtime exception.
  • Once the Delegate has been successfully built, interface method return type covariance rules apply.

Technically speaking PerfectJPattern's Delegates implementation is type-safe, you will never get a Runtime error due to a data type mismatch operation while using PerfectJPattern API i.e. you will never get a ClassCastException. If you do, then it is a bug and will need to be fixed. Note that while the possible error has been shifted from Compiler to Runtime, technically speaking this is not type-unsafe. What happens is that PerfectJPattern's implementation will detect the erroneous situation at the framework level and translate it into a precondition violation at the API level using e.g. IllegalArgumentException. Precondition violations are to be discovered at testing time by having adequate test coverage in place.

UML Class Design