To show that Qi4j is not necessarily complex, not hard to get going with and easy to deploy, we are first showing the classic HelloWorld, as small as it can get and still be Composite Oriented Programming and not only standard OOP.Ready, Set, Go!
Let's say we want to do the common HelloWorld example, but with a more domain-oriented setting. We have a Speaker interface that does the talking;
public interface Speaker
{
String sayHello();
}
Speaker.javaQi4j is an implementation of Composite Oriented Programming. So, we need a Composite for our domain model. We are creating a PoliticianComposite, that among other things can talk, via the Speaker interface. We create a PoliticianComposite that extends from the Composite interface and our Speaker interface. But we also need an implementation for Speaker, which we also declare in our Composite, the @Mixins( SpeakerMixin.class ).
import org.qi4j.api.mixin.Mixins;
import org.qi4j.api.composite.Composite;
import org.qi4j.api.composite.TransientComposite;
@Mixins( SpeakerMixin.class )
public interface PoliticianComposite
extends TransientComposite, Speaker // +others
{
}
PoliticianComposite.javaAnd of course, the simple implementation of the Speaker interface. In this case, return a String with the content "Hello, World!".
public class SpeakerMixin
implements Speaker
{
public String sayHello()
{
return "Hello, World!";
}
}
SpeakerMixin.javaSo far so good. We now need to make this into something that can run. This can be done like this;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.bootstrap.SingletonAssembler;
import org.qi4j.api.composite.TransientBuilderFactory;
public class Main
{
public static void main( String[] args )
{
SingletonAssembler assembler = new SingletonAssembler()
{
public void assemble( ModuleAssembly assembly )
throws AssemblyException
{
assembly.addTransients( PoliticianComposite.class );
}
};
TransientBuilderFactory factory = assembler.transientBuilderFactory();
Speaker speaker = factory.newTransient( PoliticianComposite.class );
System.out.println( speaker.sayHello() );
}
}
Main.javaThe SingletonAssembler creates the simplest Qi4j Runtime. It provides access to a CompositeBuilderFactory, from which we can instantiate our PoliticianComposite as a Speaker.
Done!