Strategy Pattern

Reading Time: < 1 minute

This pattern is listed in Behavioral pattern which allows you to define sets of algorithms in the parent class which will be extended by sub classes in which all the given algorithms are interchangeable. The best way to observe this pattern is to study the below example.

public abstract class Employee {

    public abstract int calculateSalary(int salary);
}

class Manager extends Employee {

    @Override
    public int calculateSalary(int salary) {
        return salary * 4;
    }
}

class Engineer extends Employee {

    @Override
    public int calculateSalary(int salary) {
        return salary * 3;
    }
}

class Technician extends Employee {

    @Override
    public int calculateSalary(int salary) {
        return salary * 2;
    }
}

class Main {

    public static void main(String[] args) {
        Employee employee;
        int managerSalary;
        int engineerSalary;
        int technicianSalary;

        //Calculate Manager's Salary and print the value
        employee = new Manager();
        managerSalary = employee.calculateSalary(1000);
        System.out.println("Manager's Salary: " + managerSalary);

        //Calculate Engineer's Salary and print the value
        employee = new Engineer();
        engineerSalary = employee.calculateSalary(1000);
        System.out.println("Engineers's Salary: " + engineerSalary);

        //Calculate Technician's Salary and print the value
        employee = new Technician();
        technicianSalary = employee.calculateSalary(1000);
        System.out.println("Technician's Salary: " + technicianSalary);
    }
}

As you’ve evaluated the example, the parent class has a globally defined method called calculateSalary and it is calculations vary for each employee, in each employees class we alter the contents and return value of the regarding method so that we can proceed the calculation for each personnel.