Sobes.tech
Junior — Middle

What design pattern is used to determine the order of object comparison?

sobes.tech AI

Answer from AI

The Strategy design pattern is usually used to determine the order of object comparison.

It allows defining a family of comparison algorithms, encapsulating each one, and making them interchangeable.

In Java, this is often implemented through the Comparator<T> interface, which defines a method for comparing two objects.

Example:

import java.util.*;

class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// Strategy for comparison by age
class AgeComparator implements Comparator<Person> {
    public int compare(Person p1, Person p2) {
        return Integer.compare(p1.age, p2.age);
    }
}

// Usage
List<Person> people = Arrays.asList(new Person("Alice", 30), new Person("Bob", 25));
Collections.sort(people, new AgeComparator());

Thus, the Strategy pattern allows changing the comparison logic without modifying the object classes.

What design pattern is used to determine the order of… - sobes.tech