Saturday 11 April 2015

Inversion of control

Class ArrangeDuties
{
    Employee e;

    ArrangeDuties(int type)
    {
if(type==1)
           e = TechEmp();
else if(type==2)
           e = HREmp();
    }

    public void allocateDuties()
    {
e.allocateDuties();
    }
}

class TechEmp()
{
    public void allocateDuties()
    {
    }  
}

class HREmp()
{
    allocateDuties()
    {
    }  
}


Class User
{
    public static void main(String args[])
    {
ArrangeDuties a = new ArrangeDuties(1);
a.allocateDuties();
    }

}


Right now ArrangeDuties is controlling how to create object and which object to create.
This ArrangeDuties  and Emplyee classes are tightly coupled.

Take away tight coupling by inverting who we create the Employee objects



Class ArrangeDuties
{
    Employee e;

    ArrangeDuties(Employee e)
    {
this.e = e;
    }

    allocateDuties()
    {
e.allocateDuties();
    }
}

class TechEmp()
{
     public void  allocateDuties()
    {
    }  
}

class HREmp()
{
    public void allocateDuties()
    {
    }  
}


Class User
{
    public static void main(String args[])
    {
Employee e = new TechEmp();
ArrangeDuties a = new ArrangeDuties(e);
a.allocateDuties();
    }
}


Now control is inverted. User class is deciding which object to make and ArrangeDuties is independent of that.