software-mariodiana
11/8/2016 - 2:05 AM

An example of simple dependency injection.

An example of simple dependency injection.

import java.util.function.Supplier;

/**
 * Simple example of dependency injection.
 *
 * <p>
 * No interface or factory is required, and the class comes with a default implementation.
 */
public class DIGreeter {
    // Default implementation.
    private static Supplier<DIGreeter> _factory = () -> new DIGreeter();

    /**
     * Set static factory to return custom implementation.
     */
    public static void setCreationFactory(Supplier<DIGreeter> factory) {
        _factory = factory;
    }

    /**
     * Return new instance via static factory method.
     */
    public static DIGreeter create() {
        return _factory.get();
    }

    /**
     * Return greeting as String.
     */
    public String sayHello() {
        return "Hello";
    }

    /**
     * Create new instance.
     */
    protected DIGreeter() {
    }
}