当前位置: 首页 > article >正文

Java集合设计模式面试题

Java集合设计模式面试题

迭代器模式

Q1: Java集合框架中的迭代器模式是如何实现的?

迭代器模式提供了一种统一的方式来访问集合中的元素,而不需要暴露集合的内部结构。

public class IteratorPatternExample {
    // 1. 基本迭代器使用
    public void basicIteratorUsage() {
        List<String> list = new ArrayList<>();
        Iterator<String> iterator = list.iterator();
        
        while (iterator.hasNext()) {
            String element = iterator.next();
            // 处理元素
        }
    }
    
    // 2. 自定义迭代器实现
    public class CustomCollection<E> implements Iterable<E> {
        private Object[] elements;
        private int size;
        
        @Override
        public Iterator<E> iterator() {
            return new CustomIterator();
        }
        
        private class CustomIterator implements Iterator<E> {
            private int cursor;
            private int lastRet = -1;
            
            @Override
            public boolean hasNext() {
                return cursor < size;
            }
            
            @SuppressWarnings("unchecked")
            @Override
            public E next() {
                if (cursor >= size)
                    throw new NoSuchElementException();
                lastRet = cursor;
                return (E) elements[cursor++];
            }
            
            @Override
            public void remove() {
                if (lastRet < 0)
                    throw new IllegalStateException();
                CustomCollection.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
            }
        }
    }
}

组合模式

Q2: Java集合框架中如何应用组合模式?

组合模式允许将对象组合成树形结构来表示"部分-整体"的层次结构。

public class CompositePatternExample {
    // 1. 组件接口
    public interface Component {
        void operation();
    }
    
    // 2. 叶子节点
    public class Leaf implements Component {
        private String name;
        
        public Leaf(String name) {
            this.name = name;
        }
        
        @Override
        public void operation() {
            System.out.println("Leaf " + name + " operation");
        }
    }
    
    // 3. 组合节点
    public class Composite implements Component {
        private List<Component> children = new ArrayList<>();
        private String name;
        
        public Composite(String name) {
            this.name = name;
        }
        
        public void add(Component component) {
            children.add(component);
        }
        
        public void remove(Component component) {
            children.remove(component);
        }
        
        @Override
        public void operation() {
            System.out.println("Composite " + name + " operation");
            for (Component child : children) {
                child.operation();
            }
        }
    }
    
    // 使用示例
    public void demonstrateComposite() {
        Composite root = new Composite("Root");
        Composite branch1 = new Composite("Branch1");
        Composite branch2 = new Composite("Branch2");
        
        Leaf leaf1 = new Leaf("Leaf1");
        Leaf leaf2 = new Leaf("Leaf2");
        Leaf leaf3 = new Leaf("Leaf3");
        
        root.add(branch1);
        root.add(branch2);
        branch1.add(leaf1);
        branch1.add(leaf2);
        branch2.add(leaf3);
        
        root.operation();
    }
}

观察者模式

Q3: 如何在集合中实现观察者模式?

观察者模式用于建立对象之间的一对多依赖关系。

public class ObserverPatternExample {
    // 1. 观察者接口
    public interface CollectionObserver {
        void onElementAdded(Object element);
        void onElementRemoved(Object element);
    }
    
    // 2. 可观察集合
    public class ObservableCollection<E> {
        private List<E> list = new ArrayList<>();
        private List<CollectionObserver> observers = new ArrayList<>();
        
        public void addObserver(CollectionObserver observer) {
            observers.add(observer);
        }
        
        public void removeObserver(CollectionObserver observer) {
            observers.remove(observer);
        }
        
        public void add(E element) {
            list.add(element);
            notifyElementAdded(element);
        }
        
        public void remove(E element) {
            if (list.remove(element)) {
                notifyElementRemoved(element);
            }
        }
        
        private void notifyElementAdded(E element) {
            for (CollectionObserver observer : observers) {
                observer.onElementAdded(element);
            }
        }
        
        private void notifyElementRemoved(E element) {
            for (CollectionObserver observer : observers) {
                observer.onElementRemoved(element);
            }
        }
    }
    
    // 3. 具体观察者
    public class CollectionMonitor implements CollectionObserver {
        @Override
        public void onElementAdded(Object element) {
            System.out.println("Element added: " + element);
        }
        
        @Override
        public void onElementRemoved(Object element) {
            System.out.println("Element removed: " + element);
        }
    }
}

装饰器模式

Q4: Java集合框架中的装饰器模式是如何使用的?

装饰器模式允许动态地给对象添加额外的职责。

public class DecoratorPatternExample {
    // 1. 同步装饰器
    public void synchronizedDecorator() {
        List<String> list = new ArrayList<>();
        List<String> syncList = Collections.synchronizedList(list);
        
        // 线程安全的操作
        syncList.add("element");
    }
    
    // 2. 不可修改装饰器
    public void unmodifiableDecorator() {
        List<String> list = new ArrayList<>();
        list.add("element");
        List<String> unmodifiableList = Collections.unmodifiableList(list);
        
        try {
            unmodifiableList.add("new element"); // 抛出异常
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify unmodifiable list");
        }
    }
    
    // 3. 自定义装饰器
    public class LoggingList<E> implements List<E> {
        private final List<E> delegate;
        
        public LoggingList(List<E> delegate) {
            this.delegate = delegate;
        }
        
        @Override
        public boolean add(E e) {
            System.out.println("Adding element: " + e);
            return delegate.add(e);
        }
        
        @Override
        public E remove(int index) {
            System.out.println("Removing element at index: " + index);
            return delegate.remove(index);
        }
        
        // 实现其他List接口方法...
    }
}

策略模式

Q5: 如何在集合中应用策略模式?

策略模式定义了算法族,分别封装起来,让它们之间可以互相替换。

public class StrategyPatternExample {
    // 1. 排序策略
    public interface SortStrategy<T> {
        void sort(List<T> list);
    }
    
    public class NaturalOrderStrategy<T extends Comparable<T>> 
            implements SortStrategy<T> {
        @Override
        public void sort(List<T> list) {
            Collections.sort(list);
        }
    }
    
    public class ReverseOrderStrategy<T extends Comparable<T>> 
            implements SortStrategy<T> {
        @Override
        public void sort(List<T> list) {
            Collections.sort(list, Collections.reverseOrder());
        }
    }
    
    // 2. 使用策略的集合
    public class StrategicList<E extends Comparable<E>> {
        private List<E> list = new ArrayList<>();
        private SortStrategy<E> sortStrategy;
        
        public void setSortStrategy(SortStrategy<E> strategy) {
            this.sortStrategy = strategy;
        }
        
        public void sort() {
            if (sortStrategy == null) {
                throw new IllegalStateException("No sort strategy set");
            }
            sortStrategy.sort(list);
        }
        
        public void add(E element) {
            list.add(element);
        }
    }
    
    // 使用示例
    public void demonstrateStrategy() {
        StrategicList<Integer> list = new StrategicList<>();
        list.add(3);
        list.add(1);
        list.add(2);
        
        // 使用自然顺序
        list.setSortStrategy(new NaturalOrderStrategy<>());
        list.sort();
        
        // 使用逆序
        list.setSortStrategy(new ReverseOrderStrategy<>());
        list.sort();
    }
}

工厂模式

Q6: 如何使用工厂模式创建集合?

工厂模式用于创建对象,而不暴露创建逻辑。

public class CollectionFactoryExample {
    // 1. 简单工厂
    public class CollectionFactory {
        public static <T> Collection<T> createCollection(String type) {
            switch (type.toLowerCase()) {
                case "list":
                    return new ArrayList<>();
                case "set":
                    return new HashSet<>();
                case "queue":
                    return new LinkedList<>();
                default:
                    throw new IllegalArgumentException("Unknown type: " + type);
            }
        }
    }
    
    // 2. 抽象工厂
    public interface CollectionAbstractFactory<T> {
        List<T> createList();
        Set<T> createSet();
        Queue<T> createQueue();
    }
    
    public class SynchronizedCollectionFactory<T> 
            implements CollectionAbstractFactory<T> {
        @Override
        public List<T> createList() {
            return Collections.synchronizedList(new ArrayList<>());
        }
        
        @Override
        public Set<T> createSet() {
            return Collections.synchronizedSet(new HashSet<>());
        }
        
        @Override
        public Queue<T> createQueue() {
            return new ConcurrentLinkedQueue<>();
        }
    }
    
    // 使用示例
    public void demonstrateFactory() {
        // 使用简单工厂
        Collection<String> list = CollectionFactory.createCollection("list");
        
        // 使用抽象工厂
        CollectionAbstractFactory<String> factory = 
            new SynchronizedCollectionFactory<>();
        List<String> syncList = factory.createList();
        Set<String> syncSet = factory.createSet();
        Queue<String> concurrentQueue = factory.createQueue();
    }
}

面试关键点

  1. 理解设计模式在集合框架中的应用
  2. 掌握迭代器模式的实现原理
  3. 了解组合模式的使用场景
  4. 熟悉观察者模式的实现方式
  5. 掌握装饰器模式的应用
  6. 理解策略模式的优势
  7. 熟悉工厂模式的不同实现
  8. 考虑设计模式的性能影响

http://www.kler.cn/a/563583.html

相关文章:

  • 5 分钟用满血 DeepSeek R1 搭建个人 AI 知识库(含本地部署)
  • 十一、大数据治理平台总体功能架构
  • leetcode 541. 反转字符串 II 简单
  • Document对象
  • docker 安装 seafile 企业云盘
  • flask 是如何分发请求的?
  • PHP-create_function
  • 【linux配置】 修改内核网络参数
  • Unity基础——世界坐标系(Global)和本地坐标系(Local)
  • 安装react报错
  • 003 SpringBoot集成Kafka操作
  • Spring MVC 面试题及答案整理,最新面试题
  • MySQL压缩版安装详细图解
  • 如何使用Java爬虫按关键字搜索VIP商品实践指南
  • 点云配准技术的演进与前沿探索:从传统算法到深度学习融合(2)
  • 学习笔记06——JVM调优
  • 【算法】797. 差分
  • 蓝桥杯嵌入式客观题以及解释
  • 谷歌推出PaliGemma 2 mix:用于多任务的视觉语言模型,开箱即用。
  • 计算机毕业设计SpringBoot+Vue.js民宿在线预定平台(源码+文档+PPT+讲解)