Last active
August 29, 2015 14:19
-
-
Save up1/856d68b29497df0167b4 to your computer and use it in GitHub Desktop.
Demo :: Composition over Inhertiance
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
abstract class Employee { | |
public int id; | |
public abstract void accept(EmployeeVisitor employeeVisitor); | |
} | |
class HourEmployee extends Employee { | |
@Override | |
public void accept(EmployeeVisitor employeeVisitor) { | |
employeeVisitor.visit(this); | |
} | |
} | |
class SalaryEmployee extends Employee{ | |
@Override | |
public void accept(EmployeeVisitor employeeVisitor) { | |
employeeVisitor.visit(this); | |
} | |
} |
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
interface EmployeeVisitor { | |
void visit(HourEmployee hourEmployee); | |
void visit(SalaryEmployee salaryEmployee); | |
} |
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
abstract class Employee { | |
public abstract String generateReport(); | |
} | |
class HourEmployee extends Employee { | |
@Override | |
public String generateReport() { | |
return null; | |
} | |
} | |
class SalaryEmployee extends Employee{ | |
@Override | |
public String generateReport() { | |
return null; | |
} | |
} |
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
class HourReport implements EmployeeVisitor { | |
public void visit(HourEmployee hourEmployee) { | |
System.out.println("Report of hour employee : " + hourEmployee.id); | |
} | |
public void visit(SalaryEmployee salaryEmployee) { | |
} | |
} |
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
HourReport hourReport = new HourReport(); | |
employees.stream().forEach(p->p.accept(hourReport)); | |
## ผลลัพธ์ ## | |
Report of hour employee : 1 | |
Report of hour employee : 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment