tdudzik

SOLID - Open/Closed Principle

Apr 11th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. /* Open/Closed Principle */
  2.  
  3. // Before
  4. class Employee {
  5.  
  6.     public enum EmployeeType {
  7.         DIRECTOR, SOFTWARE_ENGINEER, DESIGNER;
  8.     }
  9.  
  10.     private final EmployeeType type;
  11.  
  12.     public Employee(EmployeeType type) {
  13.         this.type = type;
  14.     }
  15.  
  16.     public EmployeeType getType() {
  17.         return type;
  18.     }
  19.  
  20. }
  21.  
  22. class PayCalculator {
  23.  
  24.     public BigDecimal calculatePay(Employee employee) {
  25.         BigDecimal baseSalary;
  26.         switch (employee.getType()) {
  27.             case DIRECTOR:
  28.                 baseSalary = new BigDecimal("300000");
  29.                 break;
  30.             case SOFTWARE_ENGINEER:
  31.                 baseSalary = new BigDecimal("150000");
  32.                 break;
  33.             case DESIGNER:
  34.                 baseSalary = new BigDecimal("120000");
  35.                 break;
  36.             default:
  37.                 throw new AssertionError();
  38.         }
  39.         // Calculate pay here
  40.         return new BigDecimal("");
  41.     }
  42.  
  43. }
  44.  
  45. // After
  46. class Employee {
  47.  
  48.     public enum EmployeeType {
  49.         DIRECTOR(new BigDecimal("300000")),
  50.         SOFTWARE_ENGINEER(new BigDecimal("150000")),
  51.         DESIGNER(new BigDecimal("120000"));
  52.  
  53.         private final BigDecimal baseSalary;
  54.  
  55.         EmployeeType(BigDecimal baseSalary) {
  56.             this.baseSalary = baseSalary;
  57.         }
  58.  
  59.         public BigDecimal getBaseSalary() {
  60.             return baseSalary;
  61.         }
  62.  
  63.     }
  64.  
  65.     private final EmployeeType type;
  66.  
  67.     public Employee(EmployeeType type) {
  68.         this.type = type;
  69.     }
  70.  
  71.     public BigDecimal getBaseSalary() {
  72.         return type.getBaseSalary();
  73.     }
  74.  
  75. }
  76.  
  77. class PayCalculator {
  78.  
  79.     public BigDecimal calculatePay(Employee employee) {
  80.         BigDecimal baseSalary = employee.getBaseSalary();
  81.         // Calculate
  82.         return new BigDecimal("");
  83.     }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment