Skip to content

Instantly share code, notes, and snippets.

@wightwulf1944
Created November 22, 2019 10:02
Show Gist options
  • Save wightwulf1944/74c66752b9bd7a198a8b7b1b3d699a33 to your computer and use it in GitHub Desktop.
Save wightwulf1944/74c66752b9bd7a198a8b7b1b3d699a33 to your computer and use it in GitHub Desktop.
Decorator pattern demonstration
// Only a data class. DO NOT ADD BEHAVIORS
public class Employee {
public Instant dateOfBirth;
public BigDecimal salary;
public float yearsInService;
}
public class ProfileController {
private void someFoo(ProfileEmployee employee) {
int age = employee.getAge();
boolean isNewHire = employee.isNewHire();
}
private static class ProfileEmployee {
private Employee employee;
public ProfileEmployee(Employee employee) {
this.employee = employee;
}
public int getAge() {
return (int) ChronoUnit.YEARS.between(Instant.now(), employee.dateOfBirth);
}
public boolean isNewHire() {
return employee.yearsInService < 0.5;
}
}
}
public class SalaryController {
private static final BigDecimal loyaltyBonusMaxSalary = new BigDecimal("12345"); // arbitrary value
private void someFoo(SalaryEmployee employee) {
boolean eligibleForLoyaltyBonus = employee.isEligibleForLoyaltyBonus();
double taxRate = employee.getTaxRate();
}
private static class SalaryEmployee {
private final Employee employee;
public SalaryEmployee(Employee employee) {
this.employee = employee;
}
public boolean isEligibleForLoyaltyBonus() {
return (employee.salary.compareTo(loyaltyBonusMaxSalary) < 0) &&
employee.yearsInService > 3;
}
public double getTaxRate() {
// imagine some algorithm to calculate the employees tax rate
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment