Skip to content

Instantly share code, notes, and snippets.

@gavinking
Last active October 17, 2016 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gavinking/796bc92790af4cd3db54a88853518c56 to your computer and use it in GitHub Desktop.
Save gavinking/796bc92790af4cd3db54a88853518c56 to your computer and use it in GitHub Desktop.
Ceylon Web Runner: Ceylon Services

Ceylon Services Example

This tiny example demonstrates the use of Ceylon service providers in the JavaScript environment. Service providers are an abstraction of, and interoperate with, Java's service loaders, but are not tied to the Java platform, and can even work cross-platform.

Usually, the service interface, service provider, and client of the service are defined in two or three separate Ceylon modules. But due to the limitations of the Web IDE, they're all defined in the same module in this example.

/*
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");
}
}
module web_ide_script "1.0.0" {
// Add module imports here
}
@gavinking
Copy link
Author

Click here to run this code online

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment