-
Notifications
You must be signed in to change notification settings - Fork 3
03. First program
Let's create our first Yadic program. To use Yadic we need to import com.googlecode.yadic. To interact with the library we need an instance of a Container.
import com.googlecode.yadic.*;
public class YadicTutorial {
public static void main(String[] args) {
Container container = new SimpleContainer();
}
}
Our program is not very useful in its current form, so let's add some objects to the container so that Yadic can wire them together. We are going to use instances of three classes: Car, Engine and Wheels.
public class Car {
private Engine engine; private Wheels wheels;
public Car(Engine engine, Wheels wheels) {
this.engine = engine;
this.wheels = wheels;
}
public boolean hasWheels() {
return wheels != null;
}
public boolean hasEngine() {
return engine != null;
}
}
public class Engine {} // no arg constructor
public class Wheels {} // no arg constructor
We can add objects to the container using an add method:
container.add(Engine.class);
container.add(Wheels.class);
container.add(Car.class); ...
To retrieve a fully wired object from a container we call a get method:
Car car = container.get(Car.class);
We can verify if our collaborators have been wired correctly:
System.out.println("Has engine: " + car.hasEngine()); // returns true
System.out.println("Has wheels: " + car.hasWheels()); // returns true
To summarise we give you a full program:
import com.googlecode.yadic.*;
public class YadicTutorial {
public static void main(String[] args) {
Container container = new SimpleContainer();
container.add(Engine.class);
container.add(Wheels.class);
container.add(Car.class);
Car car = container.get(Car.class);
System.out.println("Has engine: " + car.hasEngine());
System.out.println("Has wheels: " + car.hasWheels());
}
}
Yadic instantiated Wheels and Engine using their no argument constructors and then injected them to the Car object using its explicit two arguments constructor.
This was a very simple example to get you up to speed in less than 10 minutes. In the subsequent sections we will cover Yadic API in more depth and we will also explain Yadic philosophy of having many containers per application.