Java集合框架设计模式面试题
迭代器模式
Q1: 集合框架中的迭代器模式是如何实现的?
public class IteratorPatternExample {public void basicIteratorUsage() {List<String> list = new ArrayList<>();list.add("A");list.add("B");list.add("C");Iterator<String> iterator = list.iterator();while (iterator.hasNext()) {String element = iterator.next();System.out.println(element);}}public static class CustomCollection<T> implements Iterable<T> {private List<T> items = new ArrayList<>();public void add(T item) {items.add(item);}@Overridepublic Iterator<T> iterator() {return new CustomIterator<>(items);}private static class CustomIterator<T> implements Iterator<T> {private List<T> items;private int position = 0;public CustomIterator(List<T> items) {this.items = items;}@Overridepublic boolean hasNext() {return position < items.size();}@Overridepublic T next() {if (!hasNext()) {throw new NoSuchElementException();}return items.get(position++);}@Overridepublic void remove() {if (position <= 0) {throw new IllegalStateException();}items.remove(--position);}}}
}
组合模式
Q2: 集合框架如何使用组合模式?
public class CompositePatternExample {public interface Component {void operation();}public class Leaf implements Component {private String name;public Leaf(String name) {this.name = name;}@Overridepublic void operation() {System.out.println("Leaf " + name + " operation");}}public class Composite implements Component {private List<Component> children = new ArrayList<>();public void add(Component component) {children.add(component);}public void remove(Component component) {children.remove(component);}@Overridepublic void operation() {for (Component component : children) {component.operation();}}}public void demonstrateComposite() {Composite root = new Composite();Composite branch1 = new Composite();Composite branch2 = new Composite();root.add(branch1);root.add(branch2);branch1.add(new Leaf("A"));branch1.add(new Leaf("B"));branch2.add(new Leaf("C"));root.operation();}
}
适配器模式
Q3: 集合框架中的适配器模式体现在哪里?
public class AdapterPatternExample {public void arrayListAdapter() {String[] array = {"A", "B", "C"};List<String> list = Arrays.asList(array);try {list.add("D"); } catch (UnsupportedOperationException e) {System.out.println("不支持修改操作");}}public class SetToListAdapter<E> extends AbstractList<E> {private Set<E> set;public SetToListAdapter(Set<E> set) {this.set = set;}@Overridepublic E get(int index) {if (index >= set.size()) {throw new IndexOutOfBoundsException();}Iterator<E> iterator = set.iterator();for (int i = 0; i < index; i++) {iterator.next();}return iterator.next();}@Overridepublic int size() {return set.size();}}
}
装饰器模式
Q4: 集合框架如何使用装饰器模式?
public class DecoratorPatternExample {public void unmodifiableDecorator() {List<String> list = new ArrayList<>();list.add("A");list.add("B");List<String> unmodifiableList = Collections.unmodifiableList(list);try {unmodifiableList.add("C"); } catch (UnsupportedOperationException e) {System.out.println("不能修改不可变列表");}}public class LoggingList<E> extends AbstractList<E> {private List<E> list;public LoggingList(List<E> list) {this.list = list;}@Overridepublic E get(int index) {System.out.println("Getting element at index: " + index);return list.get(index);}@Overridepublic void add(int index, E element) {System.out.println("Adding element at index: " + index);list.add(index, element);}@Overridepublic E remove(int index) {System.out.println("Removing element at index: " + index);return list.remove(index);}@Overridepublic int size() {return list.size();}}
}
工厂模式
Q5: 集合框架中的工厂模式是如何体现的?
public class FactoryPatternExample {public static class CollectionFactory {public static <T> List<T> createList(boolean synchronized_) {return synchronized_ ? Collections.synchronizedList(new ArrayList<>()) :new ArrayList<>();}public static <T> Set<T> createSet(boolean sorted) {return sorted ? new TreeSet<>() : new HashSet<>();}public static <K, V> Map<K, V> createMap(boolean synchronized_, boolean sorted) {if (synchronized_) {return sorted ? Collections.synchronizedMap(new TreeMap<>()) :Collections.synchronizedMap(new HashMap<>());} else {return sorted ? new TreeMap<>() : new HashMap<>();}}}public void demonstrateFactory() {List<String> syncList = CollectionFactory.createList(true);Set<Integer> sortedSet = CollectionFactory.createSet(true);Map<String, Integer> syncSortedMap = CollectionFactory.createMap(true, true);}
}
Q6: 如何在实际项目中应用这些设计模式?
public class DesignPatternApplicationExample {public class CompositeIterator<E> implements Iterator<E> {private Stack<Iterator<E>> stack = new Stack<>();public CompositeIterator(Iterator<E> iterator) {stack.push(iterator);}@Overridepublic boolean hasNext() {if (stack.empty()) {return false;}Iterator<E> iterator = stack.peek();if (!iterator.hasNext()) {stack.pop();return hasNext();}return true;}@Overridepublic E next() {if (!hasNext()) {throw new NoSuchElementException();}Iterator<E> iterator = stack.peek();E item = iterator.next();if (item instanceof Iterable) {stack.push(((Iterable<E>) item).iterator());}return item;}}public class ThreadSafeListAdapter<E> extends AbstractList<E> {private final List<E> list;private final Object lock = new Object();public ThreadSafeListAdapter(List<E> list) {this.list = list;}@Overridepublic E get(int index) {synchronized (lock) {return list.get(index);}}@Overridepublic void add(int index, E element) {synchronized (lock) {list.add(index, element);}}@Overridepublic E remove(int index) {synchronized (lock) {return list.remove(index);}}@Overridepublic int size() {synchronized (lock) {return list.size();}}}
}
面试关键点
- 理解集合框架中的设计模式应用
- 掌握迭代器模式的实现
- 了解组合模式的使用场景
- 熟悉适配器模式的应用
- 掌握装饰器模式的实现
- 理解工厂模式的作用
- 能够组合使用多种设计模式
- 注意设计模式的性能影响