|
/* |
|
Ceylon services are an abstraction of |
|
the Java service loader facility, but |
|
they're completely cross-platform, and |
|
even work in the JavaScript environment. |
|
*/ |
|
|
|
|
|
/* |
|
A service interface is just any old |
|
interface or non-final class, just like |
|
in Java. (Interfaces are recommended.) |
|
*/ |
|
shared interface Greeter { |
|
shared formal void greet(String who); |
|
} |
|
|
|
|
|
/* |
|
A service provider is a concrete |
|
implementation of the service |
|
interface, annotated with the |
|
service() annotation. That's much |
|
easier than in Java! |
|
|
|
Typically, the service provider |
|
is defined in a different module |
|
to the service interface. (But |
|
here it's defined in the same |
|
module.) |
|
|
|
Note: we must explicitly specify |
|
the service interface in the |
|
annotation. |
|
*/ |
|
shared service (`interface Greeter`) |
|
class Hello() satisfies Greeter { |
|
greet(String who) => print("Hello ``who``!"); |
|
} |
|
|
|
/* |
|
Of course, we can have multiple |
|
providers of the same service. |
|
*/ |
|
shared service (`interface Greeter`) |
|
class Hola() satisfies Greeter { |
|
greet(String who) => print("Hola ``who``!"); |
|
} |
|
|
|
/* |
|
A client may obtain implementations |
|
of a service by calling |
|
Module.findServiceProviders(). |
|
|
|
This will find any implementation |
|
that is defined in a module that |
|
the given module depends on. |
|
|
|
Typically, the client is in a third |
|
module, separate from the module |
|
that defines the service, and from |
|
the module that implements the |
|
service, but this is not a |
|
requirement. |
|
*/ |
|
shared void run() { |
|
//search in all dependencies of this module |
|
for (greeter in `module`.findServiceProviders(`Greeter`)) { |
|
greeter.greet("Trompon"); |
|
} |
|
} |
Click here to run this code online