Created
August 16, 2009 19:57
-
-
Save chrislewis/168743 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
class Employee { | |
private Double dailyRate; | |
public Employee(Double dailyRate) { | |
this.dailyRate = dailyRate; | |
} | |
public Double getDailyRate() { | |
return this.dailyRate; | |
} | |
} | |
interface Calculator { | |
public Double calculate(Double dailyRate, Integer noOfDays); | |
} | |
interface Calendar { | |
public Integer noOfDays(); | |
} | |
abstract class SalaryCalculationEngine<E extends Employee> { | |
interface Context { | |
public Calculator getCalculator(); | |
public Calendar getCalendar(); | |
} | |
protected Context ctx; // This is the point of injection. | |
public Double calculate(Double dailyRate) { | |
return ctx.getCalculator().calculate(dailyRate, | |
ctx.getCalendar().noOfDays()); | |
} | |
public void payroll(List<E> employees) { | |
for(E emp : employees) | |
System.out.println(calculate(emp.getDailyRate())); | |
} | |
} | |
abstract class Class1SalaryConfig { | |
public Calculator calculator = new DefaultCalculator(); | |
public Calendar calendar = new DefaultCalendar(); | |
class DefaultCalculator implements Calculator { | |
public Double calculate(Double basic, Integer noOfDays) { | |
return basic * noOfDays; | |
} | |
} | |
class DefaultCalendar implements Calendar { | |
public Integer noOfDays() { | |
return 30; | |
} | |
} | |
} | |
class DI { | |
public static void main(String[] args) { | |
List<Employee> emps = new ArrayList<Employee>(); | |
emps.add(new Employee(500d)); | |
SalaryCalculationEngine<Employee> sal = new SalaryCalculationEngine<Employee>() { | |
{ ctx = new Class1SalaryConfigWithContext(); } | |
class Class1SalaryConfigWithContext extends Class1SalaryConfig implements Context { | |
public Calculator getCalculator() { | |
return this.calculator; | |
} | |
public Calendar getCalendar() { | |
return this.calendar; | |
} | |
} | |
}; | |
sal.payroll(emps); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment