Behavior parameterization (Strategy pattern) in Java

  • The mechanism to the passcode to the methods
  • The default method in the interface

Behavior Parameterization

It is a mechanism to parameterize the method’s behavior in the code. Similar to the strategy design pattern.

Problem Context

Let’s take an example. Design your application based on requirements.

REQUIREMENT #1

filter green cars.

public static List<Car> filterGreenCars(List<Car> cars) {
List<Car> filteredCars = new ArrayList<>();
for(Car car: cars) {
if ("green".equals(car.getColor())) {
filteredCars.add(car);
}
}
return filteredCars;
}

REQUIREMENT #2

Filter red cars

public static List<Car> filterCars(List<Car> cars, String color) {
List<Car> filterdCars = new ArrayList<>();
for (Car car : cars) {
if (color.equals(car.getColor())) {
filterdCars.add(car);
}
}
return filterdCars;
}

REQUIREMENT #3

Filter cars with a price lesser than 5L

public static List<Car> filterCheaperCars(List<Car> cars) {
List<Car> filteredCars = new ArrayList<>();
for(Car car: cars) {
if (car.getPrice() < 500000) {
filteredCars.add(car);
}
}
return filteredCars;
}

Code with Abstraction

Declare a car predicate

public interface CarPredicate {
boolean test(Car car);
}
class GreenColorCarPredicate implements CarPredicate{
@Override
public boolean test(Car car) {
return "green".equals(car.getColor());
}
}
class CheaperCarPredicate implements CarPredicate {    @Override
public boolean test(Car car) {
return car.getPrice() < 500000;
}
}
public static List<Car> filterCars(List<Car> cars, CarPredicate p) {
List<Car> filteredCars = new ArrayList<>();

for(Car car : cars) {
if (p.test(car)) {
filteredCars.add(car);
}
}

return filteredCars;
}
// Declare a car predicateclass GreenColorCarPredicate implements CarPredicate{
@Override
public boolean test(Car car) {
return "green".equals(car.getColor());
}
}// Pass instance of the predicate
filterCars(cars, new GreenColorCarPredicate());
filterCars(cars, new CarPredicate() {
@Override
public boolean test(Car car) {
return "green".equals(car.getColor());
}
});
filterCars(cars, car -> "green".equals(car.getColor()))
filterCars(cars, CarUtils::isGreen)
cars.stream()
.filter(car -> "green".equals(car))
.collect(Collectors.toList())

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store