面试题答案
一键面试策略接口设计
- 首先定义一个策略接口,该接口包含一个排序方法。以对自定义对象的
List
排序为例,假设自定义对象为Person
,包含name
和age
属性。
public interface SortingStrategy<T> {
int compare(T o1, T o2);
}
具体策略类实现
- 按年龄升序排序策略
public class AgeAscendingStrategy implements SortingStrategy<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
}
- 按名字字母顺序排序策略
public class NameAlphabeticalStrategy implements SortingStrategy<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
在集合排序操作中应用策略
- 假设
Person
类定义如下:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
- 使用策略进行排序:
import java.util.ArrayList;
import java.util.List;
public class SortingApp {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 20));
people.add(new Person("Charlie", 30));
// 使用年龄升序策略排序
SortingStrategy<Person> ageAscendingStrategy = new AgeAscendingStrategy();
sortList(people, ageAscendingStrategy);
System.out.println("按年龄升序排序: " + people);
// 使用名字字母顺序策略排序
SortingStrategy<Person> nameAlphabeticalStrategy = new NameAlphabeticalStrategy();
sortList(people, nameAlphabeticalStrategy);
System.out.println("按名字字母顺序排序: " + people);
}
private static <T> void sortList(List<T> list, SortingStrategy<T> strategy) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 0; j < list.size() - i - 1; j++) {
if (strategy.compare(list.get(j), list.get(j + 1)) > 0) {
T temp = list.get(j);
list.set(j, list.get(j + 1));
list.set(j + 1, temp);
}
}
}
}
}
在上述代码中,通过定义SortingStrategy
接口来抽象排序策略,具体的排序策略类实现该接口的compare
方法。在sortList
方法中,根据传入的不同策略对象,对List
进行不同方式的排序,从而实现了灵活、可复用的排序策略。