Design Patterns

Dependency Injection

Wiki Dependency Injection

fundamental requirement of the pattern: passing a service to a client, rather than allowing the client to build or find the service

Dependency injection involves four roles:

the injector may be referred to by other names: assembler, provider, container, factory, builder, spring, construction code, or main

Simple Example:

Inversion of Control

traditional program: your custom code calls functionality from a library

inversion of control: a framework takes care of the flow of control, and calls your custom code

it is sometimes referred to as "Hollywood Principle: Don't call us, we'll call you"

Desc: find the code to execute by reading its description from external configuration instead of with a direct reference in the code itself

Delegation

a delegator delegates something to do by another object

 class RealPrinter {    // the "delegate"
    void print() { 
        System.out.println("something"); 
    }
 }

 class Printer {    // the "delegator"
    RealPrinter p = new RealPrinter();  // create the delegate 
    void print() {
        p.print(); // calls the delegate
    }

    // to the outside world it looks like Printer actually prints.
    public static void main(String[] arguments) {
        Printer printer = new Printer();
        printer.print();
    }
 }