-1

大家好,我正在学习使用java的队列数据结构,但是我看到一个抽象类定义了一个枚举,这里定义的枚举为什么还要做得好,或者做这样设计的事情谢谢

package com.jwetherell.algorithms.data_structures;

import java.util.Arrays;


/**
 * Queue. A queue is a particular kind of abstract data type or collection in
 * which the entities in the collection are kept in order and the principal (or
 * only) operations on the collection are the addition of entities to the rear
 * terminal position and removal of entities from the front terminal position.
 * This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO
 * data structure, the first element added to the queue will be the first one to
 * be removed.
 * 
 * http://en.wikipedia.org/wiki/Queue_(abstract_data_type)
 * 
 * @author Justin Wetherell <phishman3579@gmail.com>
 */

public abstract class Queue<T> {

    public enum QueueType {
        LinkedQueue, ArrayQueue
    };

    /**
     * Enqueue the value in the queue.
     * 
     * @param value
     *            to enqueue.
     */
    public abstract void enqueue(T value);

    /**
     * Dequeue the head of the queue.
     * 
     * @return value that was dequeued.
     */
    public abstract T dequeue();

    /**
     * Does the queue contain the value. Warning this is an O(n) operation.
     * 
     * @param value
     *            to locate in the queue.
     * @return True if queue contains value.
     */
    public abstract boolean contains(T value);

    /**
     * Number of items in the queue.
     * 
     * @return number of items.
     */
    public abstract int size();

    /**
     * Create queue from QueueType.
     * 
     * @param type
     *            of queue to create.
     * @return Queue that was created.
     */
    public static <T> Queue<T> createQueue(QueueType type) {
        switch (type) {
            case ArrayQueue:
                return new ArrayQueue<T>();
            default:
                return new LinkedQueue<T>();
        }
    }

不好意思之前没说清楚问题,就是源码

4

1 回答 1

3

我相信问题是为什么我们为静态工厂方法定义了枚举(ArrayQueue和) ——以及这是否是一个好的设计。LinkedQueuecreateQueue

在我看来,这不是一个好的设计。我不会将工厂方法用于像Queue. 用户可能有他们自己的实现,Queue然后你就被这个工厂方法困住了,它不适用于新的实现。相反,只需在您需要的地方实例化您需要的实现。

只有当这是应用程序的业务规则时,我才会有队列工厂——即如果队列类型是可配置的;但即便如此 - 我永远不会在抽象Queue类中实现它。

于 2013-09-11T14:54:28.357 回答